Techniques de base pour copier des éléments de tuple
Dans cette étape, nous allons explorer les techniques de base pour copier des éléments d'un tuple à un autre. Étant donné que les tuples sont immuables, copier signifie en réalité créer un nouveau tuple avec les mêmes éléments ou des éléments sélectionnés.
Créons un nouveau fichier pour expérimenter ces techniques :
- Créez un nouveau fichier nommé
tuple_copying_basics.py dans le répertoire /home/labex/project
- Ajoutez le code suivant au fichier :
## Create a sample tuple to work with
original_tuple = (1, 2, 3, 4, 5)
print("Original tuple:", original_tuple)
## Method 1: Using the slice operator [:]
slice_copy = original_tuple[:]
print("\nMethod 1 - Using slice operator [:]")
print("Copy:", slice_copy)
print("Is it the same object?", original_tuple is slice_copy)
print("Do they have the same values?", original_tuple == slice_copy)
## Method 2: Using the tuple() constructor
constructor_copy = tuple(original_tuple)
print("\nMethod 2 - Using tuple() constructor")
print("Copy:", constructor_copy)
print("Is it the same object?", original_tuple is constructor_copy)
print("Do they have the same values?", original_tuple == slice_copy)
## Method 3: Using tuple unpacking (only for smaller tuples)
a, b, c, d, e = original_tuple
unpacking_copy = (a, b, c, d, e)
print("\nMethod 3 - Using tuple unpacking")
print("Copy:", unpacking_copy)
print("Is it the same object?", original_tuple is unpacking_copy)
print("Do they have the same values?", original_tuple == unpacking_copy)
## Method 4: Using the + operator with empty tuple
plus_copy = () + original_tuple
print("\nMethod 4 - Using + operator")
print("Copy:", plus_copy)
print("Is it the same object?", original_tuple is plus_copy)
print("Do they have the same values?", original_tuple == plus_copy)
- Enregistrez le fichier et exécutez-le avec la commande suivante :
python3 /home/labex/project/tuple_copying_basics.py
Vous devriez voir une sortie similaire à celle-ci :
Original tuple: (1, 2, 3, 4, 5)
Method 1 - Using slice operator [:]
Copy: (1, 2, 3, 4, 5)
Is it the same object? False
Do they have the same values? True
Method 2 - Using tuple() constructor
Copy: (1, 2, 3, 4, 5)
Is it the same object? False
Do they have the same values? True
Method 3 - Using tuple unpacking
Copy: (1, 2, 3, 4, 5)
Is it the same object? False
Do they have the same values? True
Method 4 - Using + operator
Copy: (1, 2, 3, 4, 5)
Is it the same object? False
Do they have the same values? True
Souvent, vous souhaiterez peut-être copier uniquement des éléments spécifiques ou transformer des éléments lors de la copie. Explorons ces techniques :
- Créez un nouveau fichier nommé
tuple_selective_copying.py avec le contenu suivant :
original_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("Original tuple:", original_tuple)
## Copying a slice (subset) of the tuple
partial_copy = original_tuple[2:7] ## Elements from index 2 to 6
print("\nPartial copy (indexes 2-6):", partial_copy)
## Copying with step
step_copy = original_tuple[::2] ## Every second element
print("Copy with step of 2:", step_copy)
## Copying in reverse order
reverse_copy = original_tuple[::-1]
print("Reversed copy:", reverse_copy)
## Transforming elements while copying using a generator expression
doubled_copy = tuple(x * 2 for x in original_tuple)
print("\nCopy with doubled values:", doubled_copy)
## Copying only even numbers
even_copy = tuple(x for x in original_tuple if x % 2 == 0)
print("Copy with only even numbers:", even_copy)
## Creating a new tuple by combining parts of the original tuple
first_part = original_tuple[:3]
last_part = original_tuple[-3:]
combined_copy = first_part + last_part
print("\nCombined copy (first 3 + last 3):", combined_copy)
- Enregistrez le fichier et exécutez-le :
python3 /home/labex/project/tuple_selective_copying.py
Sortie attendue :
Original tuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Partial copy (indexes 2-6): (3, 4, 5, 6, 7)
Copy with step of 2: (1, 3, 5, 7, 9)
Reversed copy: (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Copy with doubled values: (2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
Copy with only even numbers: (2, 4, 6, 8, 10)
Combined copy (first 3 + last 3): (1, 2, 3, 8, 9, 10)
Ces exemples montrent diverses façons de créer de nouveaux tuples à partir de tuples existants. Rappelez-vous :
- Le slicing (
[start:end], [::step]) est un moyen facile de créer un nouveau tuple avec un sous-ensemble d'éléments
- Les expressions de générateur sont utiles pour transformer les éléments au fur et à mesure que vous les copiez
- La concaténation de tuples avec l'opérateur
+ permet de combiner des tuples
Dans la prochaine étape, nous comparerons les performances de ces méthodes et explorerons des techniques plus avancées.