Member-only story
Master Python Tuples: Tips, Tricks, and Advanced Techniques
Explore the power of immutable sequences with Python tuples. Discover tips, tricks, and common uses to optimize your code.
What is tuple in Python?
Tuple: A Python tuple is a fixed collection of items.
# Tuple
_tuple = ("apple",) # Tuple with Single Element
_tuple = ("apple", "banana") # Tuple with Multiple Elements
# Not a tuple
_not_tuple = ("apple")Tuple unpacking with the use of the splat(*) operator:
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green) # Output: apple
print(yellow) # Output: banana
print(red) # Output: ['cherry', 'strawberry', 'raspberry'] -> List
print(tuple(red)) # Output: ('cherry', 'strawberry', 'raspberry') -> TupleTuple Repetition:
fruits = ("apple", "banana", "cherry")
more_fruits = fruits * 2
print(more_fruits) # Output: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry') -> TupleWho says tuples are immutable? Let’s have somefun…
# Tuple Concatenation
fruit = ("apple",)
fruits = fruit + ("banana",)
print(fruits) # Output: ('apple', 'banana') -> Tuple
print(fruit + fruit) # Output: ('apple', 'apple') -> Tuple
# Removing element from tuple
fruits = ("apple", "banana", "cherry")
fruits_list = list(fruits)
fruits_list.remove("banana")
fruits = tuple(fruits_list)
print(fruits) # Output: ('apple', 'cherry')Other list methods can be applied to a fruits_list, and then it can be converted back into a tuple.









