Sitemap
The Pythoneers

Your home for innovative tech stories about Python and its limitless possibilities. Discover, learn, and get inspired.

Member-only story

Master Python Tuples: Tips, Tricks, and Advanced Techniques

1 min readAug 26, 2024

--

Press enter or click to view image in full size

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') -> Tuple

Tuple Repetition:

fruits = ("apple", "banana", "cherry")
more_fruits = fruits * 2
print(more_fruits) # Output: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry') -> Tuple

Who 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.

--

--

Tushar Bosamiya
Tushar Bosamiya

Written by Tushar Bosamiya

Self-taught Dev. sharing insights on software development, Python, Data Engineering, AWS, GCP and Azure. Follow for innovative and valuable software insights!

The Pythoneers
The Pythoneers

Published in The Pythoneers

Your home for innovative tech stories about Python and its limitless possibilities. Discover, learn, and get inspired.