Python Tuples

  • Post category:python
  • Reading time:9 mins read

Tuples in Python are immutable sequences, similar to lists, but with the key distinction that once created, they cannot be modified. This immutability provides certain advantages, such as being used as keys in dictionaries or elements in sets, as well as ensuring data integrity in situations where the contents should not change.

Here’s a basic overview of tuples in Python:

Creating Tuples

Tuples are created by enclosing comma-separated values within parentheses (). You can create a tuple by enclosing a sequence of elements within parentheses (). Here are a few examples.

# Creating an empty tuple
empty_tuple = ()

# Creating a tuple with elements
my_tuple = (1, 2, 3, 4, 5)

# Tuple with mixed data types
mixed_tuple = (1, "hello", 3.14, True)

# Creating a single-element tuple (note the comma after the element)
single_element_tuple = (42,)

# Without the comma, it's not recognized as a tuple
not_a_tuple = (42)  # This is not a tuple, just an integer

# Tuple can also be created without parentheses (but this is less common)
tuple_without_parentheses = 1, 2, 3

# Nested tuple
nested_tuple = (1, (2, 3), ("hello", "world"))

print("empty_tuple: ",empty_tuple)
print("my_tuple: ",my_tuple)
print("mixed_tuple: ",mixed_tuple)
print("single_element_tuple: ",single_element_tuple)
print("not_a_tuple: ",not_a_tuple)
print("tuple_without_parentheses: ",tuple_without_parentheses)
print("nested_tuple: ",nested_tuple)

# Output
empty_tuple:  ()
my_tuple:  (1, 2, 3, 4, 5)
mixed_tuple:  (1, 'hello', 3.14, True)
single_element_tuple:  (42,)
not_a_tuple:  42 # This is not a tuple, just an integer
tuple_without_parentheses:  (1, 2, 3)
nested_tuple:  (1, (2, 3), ('hello', 'world'))

Remember that tuples are immutable, so once created, you cannot modify their elements. If you try to change them, you’ll get a TypeError.

Accessing Elements of a tuple

You can access individual elements of a tuple using square brackets [] along with the index of the element you want. Remember that indexing starts from 0. For example:

my_tuple = (1, 2, 3, 4, 5)

# Accessing the first element
first_element = my_tuple[0]  
print("first_element: ",first_element)

# Accessing the third element
third_element = my_tuple[2]
print("third_element: ",third_element)

# Output
first_element:  1
third_element:  3

Accessing Elements through Negative Indexing

You can also use negative indexing to access elements from the end of the tuple. -1 refers to the last element, -2 refers to the second last element, and so on.

# Accessing the last element
last_element = my_tuple[-1]
print("last_element: ",last_element)

# Accessing the second last element
second_last_element = my_tuple[-2]
print("second_last_element: ",second_last_element)

# Output
last_element:  5
second_last_element:  4

Accessing through Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new tuple with the specified items.

thistuple = ("apple", "banana", "cherry", "orange")
print("thistuple: ",thistuple[2:4])

# By leaving out the start value, the range will start at the first item:
thistuple = ("apple", "banana", "cherry", "orange")
print("thistuple: ",thistuple[:2])

# By leaving out the end value, the range will go on to the end of the tuple:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print("thistuple: ",thistuple[2:])

# Specify negative indexes to search from the end of the tuple.
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

# Slicing to get every second element
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
every_second = my_tuple[::2]
print("thistuple: ",every_second)

# Slicing to get a reversed tuple
reversed_tuple = my_tuple[::-1]
print("reversed_tuple: ",reversed_tuple)

# Output
thistuple:  ('cherry', 'orange')
thistuple:  ('apple', 'banana')
thistuple:  ('cherry', 'orange', 'kiwi', 'melon', 'mango')
thistuple:  ('orange', 'kiwi', 'melon')
thistuple:  (1, 3, 5, 7, 9)
reversed_tuple:  (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

Check if Item Exists in Tuple

To determine if a specified item is present in a tuple use the in keyword:

thistuple = ("Sunday","Monday","Tuesday","Wednesday")
if "Monday" in thistuple:
  print("Yes, 'Monday' is present in the tuple")

# Output
Yes, 'Monday' is present in the tuple

Tuple Immutability

Tuples are immutable means they cannot be modified once created. Attempting to modify a tuple will result in an error.

my_tuple = (1,2,3,4,5)
my_tuple[0] = 10  
# This will raise an error

Workaround

Convert the tuple into a list, change the list, and convert the list back into a tuple.

my_tuple = ("Sunday", "Saturday", "Tuesday")

# Converting Tuple to List.
tup_to_list = list(my_tuple)

# Modifying items in List.
tup_to_list[1] = "Monday"

# Adding an item in the list.
tup_to_list.append("Wednesday")

# Converting List back to Tuple.
my_tuple = tuple(tup_to_list)


print("my_tuple: ",my_tuple)

# Output
my_tuple:  ('Sunday', 'Monday', 'Tuesday', 'Wednesday')

In above example, we converted the tuple my_tuple into a List. Then we modified and added items in the list and converted the list back to Tuple my_tuple.

Length of a Tuple

You can find the length of a tuple using the len() function

my_tuple = (1,2,3,4,5)
print(len(my_tuple))  
# Output
5

Tuple Packing and Unpacking

Tuples can be packed (combining multiple values into a single tuple) and unpacked (assigning values from a tuple into separate variables) conveniently

my_tuple = 1, 2, 3  # Packing
a, b, c = my_tuple  # Unpacking
print(a, b, c)  

# Output: 
1 2 3

If the number of variables is less than the number of values present in tuple, add an * to the variable name and the values will be assigned to the variable as a list.

days_tuple = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
(sun, mon, *all_other_days) = days_tuple

# Variable sun is assigned the first value of tuple.
print("sun: ",sun)

# Variable mon is assigned the second value of tuple.
print("mon: ",mon)

# Variable all_other_days is assigned all other values of tuple as a List.
print("all_other_days: ",all_other_days)

# Output
sun:  Sunday
mon:  Monday
all_other_days:  ['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

Tuple Concatenation and Repetition

Tuples can be concatenated using the + operator and repeated using the * operator:

tuple1 = (1, 2)
tuple2 = (3, 4)
concatenated_tuple = tuple1 + tuple2  

# Output: 
(1, 2, 3, 4)

repeated_tuple = tuple1 * 3  

# Output: 
(1, 2, 1, 2, 1, 2)

Iterating Through a Tuple

You can iterate a tuple using a for loop

days_tuple = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")

print("Iterating a tuple through FOR loop.")
for day in days_tuple:
  print(day)

# Output
Iterating a tuple through FOR loop.
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

You can also loop through the tuple items by referring to their index number. Use the range() and len() functions to iterate oven a tuple.

days_tuple = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
print("Iterating a tuple through index.")
for day in range(len(days_tuple)):
  print(days_tuple[day])

# Output
Iterating a tuple through index.
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Your can use tuples where you want to store a fixed sequence of elements.