Tuples are the static snapshots of data, providing a reliable and immutable record of information in code."
In Python a tuple - is an immutable, ordered sequence of items.
Similar to lists, tuples can contain elements of different data types, but cannot be modified after their creation.
Why do we need them, if we have lists?
| Advantage | Description |
|---|---|
| Memory Efficiency | Have a fixed size, which makes them more memory-efficient than lists. |
| Faster than Lists | Due to their immutability, tuples can be slightly faster than lists when iterating through large datasets. |
| Fixed Data | Ideal for storing data that shouldn't change over time, such as configuration values or constants. |
| Easier Debugging | With immutability, it's much easier to track changes and debug your code, as tuples don't change state unexpectedly. |
There are more advantages which we will see during expanding of our knowledge into the next lessons:
| Advantage | Description |
|---|---|
| Suitable as Dictionary Keys | Tuples can be used as keys in dictionaries due to their immutability. |
| Functionality in Functions | Useful for passing multiple values to and from functions, ensuring they remain unaltered. |
| Hashable | Tuples are hashable, which means they can be used as keys in sets or as unique identifiers. |
In order to create an empty tuple we can use the following syntax:
tuple_1 = ()
tuple_2 = tuple()
print(tuple_1, tuple_2)
print(type(tuple_1), type(tuple_2))() ()
<class 'tuple'> <class 'tuple'>
As with lists you can convert other iterable data types to a tuple using the tuple() constructor.
This feature is particularly useful when you need the immutability of tuples, or when a specific API requires a tuple instead of another iterable, or you want to have a representation of some data in this format.
# Converting a list to a tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)
# Converting a string to a tuple
my_string = "hello"
string_tuple = tuple(my_string)
print(string_tuple)(1, 2, 3)
('h', 'e', 'l', 'l', 'o')
You can create a tuple just asigning a few variables into with coma and parentheses.
another_tuple = 2, 'world', 1.618
print("Another tuple:", another_tuple)
print("Type:", type(another_tuple))Another tuple: (2, 'world', 1.618)
Type: <class 'tuple'>
Once a tuple is created, its elements cannot be changed, removed, or added. This immutability makes tuples a reliable data structure for storing unchangeable data.
IMPORTANT: Though, you have to understand that if the tuple has mutable objects inside, you can access and modify them there.
tuple_1 = ([1,2,3], [5,6])
print("Tuple before:", tuple_1)
print("ID before:", id(tuple_1))
# Modifying a mutable object inside the tuple
tuple_1[-1].append(4)
print("Tuple after:", tuple_1)
print("ID after:", id(tuple_1))Tuple before: ([1, 2, 3], [5, 6])
ID before: 139653455025920
Tuple after: ([1, 2, 3], [5, 6, 4])
ID after: 139653455025920
Yes, it's Python baby, but I promise, you will get used to this once understand the concept of objects and how do they work.
Note that id of the tuple hasn't changed, but id of the objects inside has.
Same as lists Python supports indexing, slicing, concatenation, multiplication, unpacking and some built-in functions.
Suppose we have the following two tuples:
first_tuple = (1, 'hello', 3.14)
second_tuple = 2, 'world', 1.618# Indexing
print(first_tuple[1])
# Slicing
print(second_tuple[1:])hello
('world', 1.618)
# Concatenation
combined_tuple = first_tuple + second_tuple
# Multiplication
repeated_tuple = first_tuple * 2
print("Combined:", combined_tuple)
print("Repeated:", repeated_tuple)Combined: (1, 'hello', 3.14, 2, 'world', 1.618)
Repeated: (1, 'hello', 3.14, 1, 'hello', 3.14)
x, y, z = first_tuple
print(f"x={x},y={y},z={z}")x=1,y=hello,z=3.14
if 'hello' in first_tuple:
print("Found 'hello' in the tuple!") Found 'hello' in the tuple!
constants = (3.14, 2.7, 36.6)
length = len(constants)
max_value = max(constants)
min_value = min(constants)
sum_value = sum(constants)
sorted_list = sorted(constants)
print("Lenght:", length)
print("Max:", max_value)
print("Min:", min_value)
print("Sum:", sum_value)
print("Sorted:", sorted_list) # Note that ``sorted()`` returns a ``list`` instead!Lenght: 3
Max: 36.6
Min: 2.7
Sum: 42.44
Sorted: [2.7, 3.14, 36.6]
Basically, it's very similar to lists, but don't forget that Python doesn't allow modification of immutable objects.
There are only two methods for tuples.
nums = (1, 2, 3)
| Method | Description | Example | Output |
|---|---|---|---|
index(x) |
Returns the index of the first item whose value is x. | nums.index(3) |
2 |
count(iterable) |
Returns the number of times x appears in the tuple. | nums.count(1) |
1 |
Typically we use tuples for stroing the constants.
# Rainbow is a constant so that ``tuple`` is a great choice to store its colors
rainbow = ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet')
for color in rainbow:
print(color)red
orange
yellow
green
blue
indigo
violet
# Tuple of prime numbers
primes = (2, 3, 5, 7, 11)
for index in range(len(primes)):
print(f"Prime number at index {index} is {primes[index]}")Prime number at index 0 is 2
Prime number at index 1 is 3
Prime number at index 2 is 5
Prime number at index 3 is 7
Prime number at index 4 is 11
There is a built-in function called enumerate(), that adds a counter to an iterable.
It can be used with any iterable. and be particulary useful with when both the element and its index are needed.
# Tuple of weekdays
weekdays = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
for index, day in enumerate(weekdays):
print(f"{day} is the {index+1}-th day of the workweek.")Monday is the 1-th day of the workweek.
Tuesday is the 2-th day of the workweek.
Wednesday is the 3-th day of the workweek.
Thursday is the 4-th day of the workweek.
Friday is the 5-th day of the workweek.
What will be the output of the following code?
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[-2])What happens when you try to modify an element in a tuple?
my_tuple = (1, 2, 3, 4, 5)
my_tuple[0] = 6Which of the following is the correct way to create a tuple?
A) my_tuple = tuple(1, 2, 3)
B) my_tuple = 1, 2, 3
C) my_tuple = (1,)
D) my_tuple = [1, 2, 3]
What does the
count()method do in a tuple?
A) Counts the number of occurrences of an element in the tuple.
B) Counts the total number of elements in the tuple.
C) Returns the first occurrence of an element in the tuple.
D) None of the above.
What is the output of the following tuple slicing?
my_tuple = (0, 1, 2, 3, 4, 5)
print(my_tuple[1:4])A) (1, 2)
B) (1, 2, 3)
C) (2, 3, 4)
D) (0, 1, 2)
How does
enumerate()enhance the iteration process intuples?
A) It sorts the tuple before iteration.
B) It adds a counter as part of the tuple element during iteration.
C) It reverses the tuple during iteration.
D) It performs unpacking of the tuple elements.
Which of the following is true about
tupleconcatenation?
A) It modifies the original tuple.
B) It creates a new tuple.
C) It's not possible to concatenate tuples.
D) It removes duplicates while concatenating.
Which of the following statements about tuples is NOT true?
A) Tuples are immutable.
B) Tuples can contain elements of different data types.
C) Tuples do not support slicing.
D) Tuples can be used as keys in dictionaries.
Objective: Write a program that allows the user to input a sequence of numbers, store them in a tuple, and analyze the tuple to provide insights.
Input: Enter numbers separated by commas: 1, 2, 3, 4, 5
Output: Tuple: (1, 2, 3, 4, 5)
Sum: 15
Average: 3
Maximum: 5
Minimum: 1Objective: Develop a program to sort elements of multiple tuples based on user preference (ascending or descending order).
Input: Enter elements of the tuple: 5, 1, 9, 3
Sort order (asc/desc): asc
Output: Sorted Tuple: (1, 3, 5, 9)Objective: Create a program that finds specific elements within a tuple based on user queries.
Input: Tuple: (1, 2, 3, 4, 5, 6)
Enter element to search: 4
Output: Element 4 found at index: 3Objective: Use the enumerate() function to list sports teams and their ranking based on user input.
Input: Enter teams (separated by commas): Lakers, Bulls, Celtics
Output: Team Rankings:
1. Lakers
2. Bulls
3. CelticsObjective: Try rewriting some programs from the previous homework where it's applicable and where tuples are a better choice.