Tuples: Immutable Data Structures
Pythons Tutorials
Tuples are data structures that allow you to group multiple items together. The crucial distinction from lists? Tuples are immutable, meaning their elements can’t be modified once set.
1. Creating Tuples:
To create a tuple, simply enclose your items in parentheses and separate them with commas.
Example: Creating Tuples
coordinates = (3, 5)
fruits = ("apple", "banana", "orange")
2. Accessing Tuple Elements:
You can access individual elements in a tuple using indexing, just like with lists.
Example: Accessing Tuple Elements
print(coordinates[0]) # Output: 3
print(fruits[1]) # Output: banana
3. Tuple Packing and Unpacking:
Tuples can also be created through tuple packing and unpacking. Packing involves grouping values into a tuple, and unpacking assigns those values to variables.
Example: Tuple Packing and Unpacking
point = 10, 20
x, y = point
print(x, y) # Output: 10 20
6. Combining Tuples:
Tuples can be combined using concatenation (joining) and repetition (duplication).
Example: Combining Tuples
fruits = ("apple", "banana")
more_fruits = ("orange", "grape")
combined_fruits = fruits + more_fruits
repeated_fruits = fruits * 3
7. Tuple Methods:
Tuples don’t offer as many methods as lists due to their immutability, but they do have a few methods like count()
and index()
.
Example: Using Tuple Methods
numbers = (1, 2, 3, 4, 3)
count_3 = numbers.count(3) # Count occurrences of 3
index_2 = numbers.index(2) # Find index of 2
7. Use Cases for Tuples:
Tuples are perfect for situations where you want to group related data that should remain unchanged, like coordinates or components of a date.