Tuple
A tuple is similar to a list, however it is immutable. A tuple can be created, but cannot be modified after creation. The elements cannot be updated or deleted. To create a tuple use parentheses () or the tuple() constructor.
Creating a Tuple
A tuple can be created by enclosing items in parentheses (), separated by commas:
empty_tuple = ()numbers = (1, 2, 3, 4)mixed = (1, 1.2, True, None, "hello")repetition = ("ABC", "ABC", "ABC")nested = ((1, 2, 3), (4, 5, 6), (7, 8, 9))A tuple can also be created using the tuple() constructor which takes an iterable and converts it into a tuple. If the iterable is already a tuple, it will return the same tuple.
chars = tuple("hello") # ('h', 'e', 'l', 'l', 'o')numbers = tuple(range(5)) # (0, 1, 2, 3, 4)Common Sequence Operations
Tuples are sequences, which means they support common sequence operations that work with other sequence types like strings and lists. These operations include:
- Membership: Check if an element exists
- Length: Get the number of elements
- Minimum and Maximum: Find the smallest and largest elements
- Counting: Count the number of occurrences of an element
- Searching: Find the index of an element
- Indexing: Access elements by their position
- Slicing: Extract portions of the tuple
- Concatenation: Combine tuples
- Repetition: Repeat tuples
Indexing, Slicing, and Immutability
Tuples support indexing and slicing just like lists. Elements can be accessed using positive indices (starting at 0) or negative indices (counting from the end), and tuples can be sliced using the same [start:stop:step] syntax. However, the key difference is that tuples are immutable: their contents cannot be changed after creation.
x = (1, 2, 3, 4, 5)
print(x[0]) # 1print(x[-1]) # 5print(x[1:4]) # (2, 3, 4)print(x[::2]) # (1, 3, 5)
x[0] = 10 # TypeError: 'tuple' object does not support item assignmentWarning
Since tuples are immutable, you cannot modify, add, or delete elements. Slicing creates a new tuple, leaving the original unchanged.
The Comma Operator and Parentheses
The comma is what actually creates a tuple, not the parentheses. Parentheses are optional in most cases, but they help with readability and are required in some contexts to avoid ambiguity.
# All of these create tuplesx = (1, 2, 3, 4, 5)y = (1, 2, 3)z = (1, 2)
# Parentheses are optionalx = 1, 2, 3, 4, 5y = 1, 2, 3z = 1, 2However, for a single-element tuple, the comma is required:
# This creates an integer, not a tuplet = (1)print(type(t)) # <class 'int'>
# This creates a tuplet = (1,)print(type(t)) # <class 'tuple'>
# Or without parenthesest = 1,print(type(t)) # <class 'tuple'>Tuple Packing and Unpacking
Tuple packing is the process of creating a tuple from values:
colors = ("red", "green", "purple")Tuple unpacking (also called destructuring) is the process of extracting values from a tuple into separate variables:
colors = ("red", "green", "purple")(primary, secondary, accent) = colors
print(primary) # redprint(secondary) # greenprint(accent) # purpleThe number of variables must match the number of elements in the tuple, otherwise Python will raise a ValueError:
colors = ("red", "green", "purple")(primary, secondary) = colors # ValueError: too many values to unpack (expected 2)Extended Unpacking with Asterisk
If the number of variables doesn’t match the number of elements, an asterisk * can be used to collect the remaining elements into a list:
colors = ("red", "green", "blue", "purple", "orange")
# Collect remaining elements in the middle(primary, *middle, secondary) = colorsprint(primary) # redprint(middle) # ['green', 'blue', 'purple']print(secondary) # orange
# Collect remaining elements at the end(primary, secondary, *the_rest) = colorsprint(primary) # redprint(secondary) # greenprint(the_rest) # ['blue', 'purple', 'orange']
# Collect remaining elements at the beginning(*first, last) = colorsprint(first) # ['red', 'green', 'blue', 'purple']print(last) # orangeThe size of the tuple must be at least the number of non-asterisk variables.
Swapping Variables
Tuple unpacking can be used to swap two variables without using a temporary variable:
a = 5b = 10
a, b = b, a
print(a) # 10print(b) # 5Another example with more than two variables:
a = 5b = 6c = 7d = 8
a, b, c, d = d, c, b, aLooping, Membership, and Operators
Tuples support the same iteration and operator behaviors as lists: you can loop through tuples using for or while loops, check membership with in and not in, and use identity operators is and is not. The assignment operator works the same way, but since tuples are immutable, assigning a tuple to multiple variables is safe—there’s no risk of accidentally modifying one variable and affecting another.
fruits = ("apple", "banana", "orange")
# Loopingfor fruit in fruits: print(fruit)
for i in range(len(fruits)): print(i, ":", fruits[i])
i = 0while i < len(fruits): print(fruits[i]) i += 1
# Membershipprint("apple" in fruits) # Trueprint("grape" not in fruits) # True
# Assignment and identityx = (1, 2, 3)y = xprint(x is y) # Trueprint(x == y) # True (same values)Notable Tuple Methods
Notable tuple methods include:
count(e): Returns the number of occurrences ofein the tuple.index(value): Returns the first index ofvalue. Raises aValueErrorif the value is not found.
numbers = (1, 2, 3, 2, 4, 2, 5)
print(numbers.count(2)) # 3print(numbers.count(10)) # 0
print(numbers.index(2)) # 1print(numbers.index(4)) # 4print(numbers.index(10)) # ValueError: tuple.index(x): x not in tupleTuple as a Sequence
Tuples are sequences, so let’s see all the sequence operations in one example:
x = (1, 2, 3, 4, 5)
print(x) # (1, 2, 3, 4, 5)print(len(x)) # 5print(min(x)) # 1print(max(x)) # 5print(sum(x)) # 15
print(3 in x) # Trueprint(10 in x) # False
print(x.count(3)) # 1print(x.index(3)) # 2
print(x[1::2]) # (2, 4)print(x * 2) # (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)print(x + (6, 7)) # (1, 2, 3, 4, 5, 6, 7)Why Tuples Exist
A common question for Python developers is: Why do we have tuples if we have lists? When should we use one over the other?
Although they are similar, they are used in fundamentally different ways:
Tuples can be thought of as similar to C-structs, where we have a collection of elements and we are operating on all of them together (point coordinates, RGB color values, etc.). They are:
- Immutable (cannot be changed after creation)
- Can be used as dictionary keys
- More memory-efficient for fixed collections
- Indicate that the data structure is meant to be fixed
Lists are similar to arrays/vectors, where we are free to add/remove elements, and operate on each one individually. They are:
- Mutable (can be changed after creation)
- Cannot be used as dictionary keys
- Better for collections that need to grow or shrink
- Indicate that the data structure is meant to be modified
Exercises
Exercise 1: Read the size of a tuple, followed by the elements, then create a tuple and print it
Write a program that reads the size of the tuple followed by the elements, then creates a tuple and prints it.
Create Tuple from Input
size = int(input())numbers = []for i in range(size): numbers.append(int(input()))my_tuple = tuple(numbers)print(my_tuple)Exercise 2: Find the sum of the elements in a tuple
Write a program that reads the size of the tuple followed by the elements of the tuple and prints the sum of all elements in the tuple.
Sum of Tuple Elements
size = int(input())numbers = []for i in range(size): numbers.append(int(input()))my_tuple = tuple(numbers)total = 0for num in my_tuple: total += numprint(total)or
size = int(input())numbers = []for i in range(size): numbers.append(int(input()))my_tuple = tuple(numbers)print(sum(my_tuple))Exercise 3: Create a list of points from two lists
Given two lists x and y, write a program that reads the size of the lists, then reads the elements of list x, then reads the elements of list y, and prints a list of points, where each element of the list is a tuple, with the first element representing the x coordinate and the second as the y coordinate.
List of Points
size = int(input())x = []for i in range(size): x.append(int(input()))y = []for i in range(size): y.append(int(input()))points = []for i in range(size): points.append((x[i], y[i]))print(points)Exercise 4: Finding the minimum value in a tuple without the min function
Write a program that reads the size of the tuple followed by the elements of the tuple and finds the minimum value without using the min() function.
Find Minimum in Tuple
size = int(input())numbers = []for i in range(size): numbers.append(int(input()))my_tuple = tuple(numbers)minimum = my_tuple[0]for num in my_tuple: if num < minimum: minimum = numprint(minimum)Exercise 5: Count occurrences of an element in a tuple
Write a program that reads the size of the tuple followed by the elements of the tuple, then reads a target number, and counts how many times the target number appears in the tuple without using the count() method.
Count Occurrences
size = int(input())numbers = []for i in range(size): numbers.append(int(input()))my_tuple = tuple(numbers)target = int(input())count = 0for num in my_tuple: if num == target: count += 1print(count)Exercise 6: Tuple unpacking with extended unpacking
Write a program that reads 5 integers and unpacks them into variables: first, middle (a list containing the middle 3 values), and last. Print first, middle, and last on separate lines.
Extended Unpacking
a = int(input())b = int(input())c = int(input())d = int(input())e = int(input())my_tuple = (a, b, c, d, e)first, *middle, last = my_tupleprint(first)print(middle)print(last)Exercise 7: Reverse a tuple using a loop
Write a program that reads the size of the tuple followed by the elements of the tuple and creates a new tuple with the elements in reverse order using a loop (without using slicing or the reversed() function). Print the reversed tuple.
Reverse Tuple
size = int(input())numbers = []for i in range(size): numbers.append(int(input()))my_tuple = tuple(numbers)reversed_list = []for i in range(len(my_tuple) - 1, -1, -1): reversed_list.append(my_tuple[i])reversed_tuple = tuple(reversed_list)print(reversed_tuple)Exercise 8: Find the index of an element without using index() method
Write a program that reads the size of the tuple followed by the elements of the tuple, then reads a target number, and finds the first index where the target number appears without using the index() method. Print the index if found, otherwise print -1.
Find Index
size = int(input())numbers = []for i in range(size): numbers.append(int(input()))my_tuple = tuple(numbers)target = int(input())index = -1for i in range(len(my_tuple)): if my_tuple[i] == target: index = i breakprint(index)Exercise 9: Convert tuple to list and back
Write a program that reads the size of the tuple followed by the elements, creates a tuple, converts it to a list, appends a new element (read from input), converts it back to a tuple, and prints the final tuple.
Convert Tuple to List and Back
size = int(input())numbers = []for i in range(size): numbers.append(int(input()))my_tuple = tuple(numbers)my_list = list(my_tuple)new_element = int(input())my_list.append(new_element)my_tuple = tuple(my_list)print(my_tuple)