tuple¶
- Tuples in Python are another fundamental data structure used to store collections of items. They are similar to lists in some ways, but with a key difference: tuples are immutable, meaning their elements cannot be changed after creation.
- Tuples are enclosed in parentheses
()
, similar to lists, but commas are optional to separate items if you have just one or two elements. - Just like lists, elements in tuples are indexed starting from 0. You can access them using their index within square brackets.
- Negative indexing works the same way as with lists.
- Similar to lists, you can extract a portion of a tuple using slicing with square brackets and colons
- The slicing syntax ([start:end:step]) functions the same way as for lists.
- Unlike lists, tuples are immutable. This means you cannot modify elements after creating the tuple. Here's an attempt that will result in an error.
- Common Tuple Operations
len(tuple)
: Returns the length (number of items) in the tuple.in
andnot in
: Check if an element is present in the tuple.tuple(iterable)
: Can be used to convert other iterables (like lists) to tuples, but be aware that modifications to the original list won't be reflected in the tuple.
- When to Use Tuples
- Use tuples when you need a collection of items that should not be changed after creation. This helps prevent accidental modifications and ensures data integrity.
- Tuples are often used to represent fixed data sets or to store configuration values.
- They can also be used as dictionary keys since they are immutable and hashable (meaning they can be used as dictionary keys).
- Key Points
- Tuples are ordered collections of elements.
- They are immutable, offering data integrity by preventing accidental changes.
- Accessing and slicing elements work similarly to lists.
- Tuples are useful for representing fixed data sets or configuration values.
In [ ]:
Copied!
fruits = ("🍎", "🍌", "🍒") # With commas
numbers = (1, 2, 3) # Without commas (for single-line tuples)
first_fruit = fruits[0] # first_fruit will be "🍎"
last_number = numbers[-1] # last_number will be 3
subtuple = fruits[1:3] # subtuple will be ("🍌", "🍒")
fruits[0] = "🥭" # This will cause a TypeError
fruits = ("🍎", "🍌", "🍒") # With commas
numbers = (1, 2, 3) # Without commas (for single-line tuples)
first_fruit = fruits[0] # first_fruit will be "🍎"
last_number = numbers[-1] # last_number will be 3
subtuple = fruits[1:3] # subtuple will be ("🍌", "🍒")
fruits[0] = "🥭" # This will cause a TypeError
In [ ]:
Copied!
# looping through tuple
for fruit in fruits:
print(fruit)
# looping through tuple
for fruit in fruits:
print(fruit)
In [ ]:
Copied!
# comprehension
squares = (i**2 for i in range(10))
print(squares) # generator object
# comprehension
squares = (i**2 for i in range(10))
print(squares) # generator object