Tuples in Python
When data has a fixed shape (coordinates, an RGB colour, a function return value made of several parts), that's a case for a tuple, not a list. A tuple (tuple) is an ordered immutable collection: once it's created, you can't add, remove, or change its elements.
What is a tuple?
A tuple in Python is an ordered, immutable collection of elements that can be of different types. Simply put, it's like a list, but one that cannot be changed after creation.
Main properties of tuples:
- Ordered: elements are stored in a specific order
- Immutable: after creation, you cannot add, remove, or change elements
- Indexable: elements can be accessed by their indices
- Allow duplicates: they can contain repeated values
- Can contain different data types: integers, strings, lists, etc.
Creating tuples
There are several ways to create tuples in Python:
Using parentheses ()
Python 3.13# Empty tuple empty_tuple = () # Tuple with a single element (comma is required!) single_item = (42,) print(type(single_item))<class 'tuple'># Without a comma, it's just a number: (42) == 42 single_item_num = (42) print(type(single_item_num))<class 'int'># Tuple of numbers numbers = (1, 2, 3, 4, 5) # Tuple with different data types mixed = (1, "hello", True, 3.14) # Nested tuples nested = ((1, 2), ("a", "b"), (True, False))
Without parentheses (comma separation)
Python allows creating tuples even without parentheses, simply by listing elements separated by commas:
Python 3.13# Creating a tuple without parentheses coordinates = 10.5, 20.7, 30.9 print(type(coordinates))<class 'tuple'>
Using the tuple() constructor
Python 3.13# Creating an empty tuple empty_tuple = tuple() # Converting a list to a tuple list_to_tuple = tuple([1, 2, 3]) print(list_to_tuple)(1, 2, 3)# Converting a string to a tuple (each character becomes an element) string_to_tuple = tuple("Python") print(string_to_tuple)('P', 'y', 't', 'h', 'o', 'n')# Converting a set to a tuple set_to_tuple = tuple({1, 2, 3}) print(set_to_tuple)(1, 2, 3)
Accessing tuple elements
Accessing tuple elements is done the same way as in lists — through indices and slices:
Indexing
Python 3.13fruits = ("apple", "banana", "cherry", "date", "elderberry") # Getting elements by index first_fruit = fruits[0] print(first_fruit)apple# Negative indices for accessing from the end of the tuple last_fruit = fruits[-1] print(last_fruit)elderberry
Slices
Python 3.13fruits = ("apple", "banana", "cherry", "date", "elderberry") # First three elements first_three = fruits[:3] print(first_three)('apple', 'banana', 'cherry')# From second to fourth middle = fruits[1:4] print(middle)('banana', 'cherry', 'date')# Reversing the tuple reversed_tuple = fruits[::-1] print(reversed_tuple)('elderberry', 'date', 'cherry', 'banana', 'apple')
Tuple methods
Since tuples are immutable, they have only two methods:
Python 3.13fruits = ("apple", "banana", "cherry", "banana", "date") # Counting the number of occurrences of an element banana_count = fruits.count("banana") print(banana_count)2# Finding the index of the first occurrence of an element banana_index = fruits.index("banana") print(banana_index)1
Operations with tuples
Python 3.13# Finding the length fruits = ("apple", "banana", "cherry") print(len(fruits))3# Checking if an element exists print("apple" in fruits)Trueprint("mango" in fruits)False# Concatenation (combining) tuples more_fruits = ("pear", "orange") all_fruits = fruits + more_fruits print(all_fruits)('apple', 'banana', 'cherry', 'pear', 'orange')# Repetition repeated = fruits * 2 print(repeated)('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')# Unpacking a, b, c = fruits print(a, b, c)apple banana cherry
Comparing tuples
Tuples are compared element by element, left to right, until the first difference:
Python 3.13print((1, 2) < (1, 3))Trueprint((2, 0) < (1, 9))False
In the first case the first elements are equal (1 == 1), so Python moves on to the second: 2 < 3, so the whole tuple is smaller. In the second, 2 > 1 is enough on its own.
This lets you sort a list of tuples by several fields with one call:
Python 3.13people = [("Bob", 30), ("Anna", 25), ("Anna", 30)] print(sorted(people))[('Anna', 25), ('Anna', 30), ('Bob', 30)]
The sort first compares the first element (name); on a tie it falls back to the second (age).
Immutability of tuples
It's important to understand that the immutability of tuples means that after creating a tuple you cannot:
- Modify existing elements
- Add new elements
- Remove elements
Python 3.13# Creating a tuple coordinates = (10.5, 20.7, 30.9) # These operations will raise a TypeError: # coordinates[0] = 15.0 # Cannot modify an element # coordinates.append(40.2) # No append method # coordinates.remove(20.7) # No remove method # del coordinates[1] # Cannot delete an element # But you can create a new tuple based on an existing one new_coordinates = (15.0,) + coordinates[1:] print(new_coordinates)(15.0, 20.7, 30.9)
Important note about nested mutable objects
Python 3.13# Tuple containing a list tuple_with_list = (1, 2, [3, 4]) # This works because we're modifying the list inside the tuple tuple_with_list[2][0] = 30 print(tuple_with_list)(1, 2, [30, 4])# But this will raise an error - cannot modify the tuple itself # tuple_with_list[2] = [5, 6] # TypeError
Practical examples of using tuples
1. Returning multiple values from functions
Python 3.13def get_user_info(): name = "Anna" age = 30 is_admin = True return name, age, is_admin # Unpacking the result user_name, user_age, user_is_admin = get_user_info() print(f"Name: {user_name}, Age: {user_age}, Admin: {user_is_admin}")Name: Anna, Age: 30, Admin: True
2. Fixed data
Python 3.13# Days of the week - a perfect example of an immutable sequence DAYS_OF_WEEK = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") # Usage today_index = 4 # Friday print(f"Today is {DAYS_OF_WEEK[today_index]}")Today is Friday
Comparison of lists and tuples
Technically lists and tuples often overlap in what they can do, but in Python code they have different roles:
- A tuple is a "record": each position has a specific meaning. (name, age, email) isn't "a list of three random things", it's a structure where the first slot is always the name, the second always the age, the third always the email.
- A list is a homogeneous collection: all elements have roughly the same "kind", and their count can grow or shrink as the program runs.
This distinction matters more than the technical details: even when both work, your choice affects readability and intent.
Common mistakes when working with tuples
-
Forgotten comma in a single-element tuple
Python 3.13# Incorrect (this is not a tuple, just a number in parentheses) not_a_tuple = (42) print(type(not_a_tuple))<class 'int'>
# Correct single_item_tuple = (42,) print(type(single_item_tuple))<class 'tuple'>
-
Attempting to modify a tuple
Python 3.13coordinates = (10.5, 20.7, 30.9) # This will raise an error try: coordinates[0] = 15.0 except TypeError as e: print(f"Error: {e}")Error: 'tuple' object does not support item assignment
Understanding check
Which of the following statements about tuples in Python is true?
In the next lesson we'll look at sets (set) — collections where every element is unique.
