Updated July 21, 2023
Introduction to Tuples in Python
If you’re a Python programmer, you’ve probably heard about tuples. But what exactly are they? A tuple is an ordered collection of elements enclosed in parentheses and separated by commas. It’s similar to a list but with a key difference – tuples are immutable (cannot be modified), while lists are mutable.
Creating tuple in Python:
#Defining a tuple
my_tuple1 = (1,2,"a","b", True)
#Accessing element of a tuple
print(my_tuple1[0])
print(my_tuple1[2])
Output:
Table of Content
- Introduction to Tuples in Python
- Immutable nature of tuples
- Difference between Lists and Tuples
- Creating Tuples
- Accessing and Slicing Tuples
- Modifying Tuples
- Tuple Operations and Methods
- Iterating over Tuples
- Tuple Packing and Unpacking with Examples
- Tuple Comprehensions
- Practical Applications of Tuples
- Tuple Best Practices and Tips
Immutable nature of tuples
Tuples in Python possess a unique characteristic: they are immutable. This means that its elements cannot be modified once a tuple is defined. Tuples are defined using parentheses () and commas to separate the elements.
Example:
#define a tuple
my_tuple1 =(1,2,"a","b",True)
#Accessing elements of a tuple
print(my_tuple1[0]) # :output1
print(my_tuple1[2]) # :output"a"
#Attempting to modify a tuple will result in an error
my_tuple1[0] = 10 # Error: 'tuple' object does not support item assignment
Output:
The example above defines a tuple my_tuple with elements 1, 2, ‘a’, ‘b’, True, and. We can access individual elements of the tuple using indexing, just like lists. However, if we try to change an element of the tuple, it will return an error because tuples are immutable. Usually, people use tuples for grouping various related pieces of data together. For example, we can use a tuple to be the coordinates of a point in a 2D space.
The first element represents the coordinate x, and the second represents the y-coordinate. When a function returns numerous values, tuples are also helpful. You can group all the values in a tuple and return the tuple as one object as opposed to returning every value individually.
Overall, tuples are a practical way to store and access unchanging fixed data in Python.
Difference between Lists and Tuples
Python uses tuples and lists to store groups of elements. However, they have some key differences.
- Mutability: Lists are mutable, meaning their elements can be modified, added, or removed after being defined. Conversely, Tuples are immutable, and their elements cannot be modified once defined.
- Syntax: Lists are defined using square brackets [], while tuples are defined using parentheses (). example, my_list1 = [1, 2, 3, ‘a’, ‘b’] and my_tuple1 = (1, 2, 3, ‘a’, ‘b’).
- Functionality: Lists have more built-in methods and functionality than tuples. Lists provide methods like append(), remove(), and sort() that allow for dynamic modifications. Tuples, being immutable, have fewer methods available. However, both lists and tuples support common operations like indexing and slicing.
- Memory efficiency: Tuples are generally more memory-efficient than lists. Since tuples are immutable, Python can optimize their memory usage. Lists, being mutable, require additional memory allocation to accommodate potential changes.
- Usage: People often use lists when they need a collection that can be changed or updated frequently. They suit circumstances where you must add, remove, or modify elements. Programmers use tuples to maintain values that should not be changed, such as coordinates, records from databases, or function return values, rather than using triples. When to use lists and tuples:
- Use lists when you need a collection that can be modified.
- Use tuples when you need a collection that should remain constant.
Attribute | Python List | Python Tuple |
Syntax | Created using square brackets: [] | Created using regular parentheses: () |
Mutability | Items can be changed, deleted, or added to | Items cannot be changed (note in mutability section) |
Ordered | Yes | Yes |
Heterogeneous | Yes | Yes |
Size/Length | Size and length can be modified | Size and length are fixed once created |
Memory Consumption | Higher memory consumption | Lower memory consumption |
Able to Be Copied | Can have copies created | Any “copy” will point directly to the original |
It can be used as dictionary keys | No | Yes |
Iterating over items | It can be slightly slower than tuples | It can be slightly faster than lists |
Creating Tuples
1. Using parentheses
Tuples in Python can be created using parentheses(). Commas separate the elements of the tuple. Here’s an example of creating tuples using parentheses:
Example:
# Creating a tuple with integer
my_tuple1 = (1,2,3,4,5)
print(my_tuple1)
Output:
In the above example, we created a tuple my_tuple1 with integers 1, 2, 3, 4, and after that, 5. Elements are inserted within parentheses, and a comma separates each element. Then we print the tuple, which displays all the elements added in parentheses.
2. Empty tuples
In Python, you can create tuples using empty parentheses ().
Example:
#Creating an empty tuple
my_tuple1 = ()
print(my_tuple1)
Output:
In the above example of empty tuples, we create an empty tuple my_tuple1 by using parentheses; there resulting tuple is empty, indicated by the pair of parentheses with no elements inside.
3. Singleton tuples
Tuples with only one element are called singleton tuples. Even though there is just one element, Python requires that you include a comma after it to make a singleton tuple. Creating singleton tuples is demonstrated here:
Example:
#Creating a singleton tuple
my_tuple1 = ("Nick",)
print(my_tuple1)
Output:
4. Tuple packing and unpacking
Collecting several values or elements into a tuple is called tuple packing. On the opposite hand, tuple unpacking entails designating the components of a tuple to specific variables. A few instances of tuple packing and unpacking are as follows:
Examples:
# Packing a tuple
tuple_1 = 1, 2, 3 # No need for parentheses
print(tuple_1)# (1, 2, 3)
tuple_2 = ('a', 'b', 'c')
print(tuple_2)# ('a', 'b', 'c')
# Unpacking a tuple
a, b, c = tuple_1
print(a, b, c)# 1 2 3
x, y, z = tuple_2
print(x, y, z)# a b c
Output:
Accessing and Slicing Tuples
Tuples in Python can be accessed and sliced using indexing and slicing operations. Accessing tuple elements allows you to retrieve specific values, while slicing enables you to extract subsets of data from tuples. Let’s explore these concepts in detail with examples and their corresponding outputs:
Accessing Tuple Elements:
Tuple elements can be accessed using indexing, which starts from 0 for the first element. To access a specific element, use the tuple name followed by the index in square brackets.
Example:
my_tuple1 = (8,6,2,'h','f')
print(my_tuple1[0])
print(my_tuple1[3])
Output:
Slicing Tuples:
You can slice tuples in Python to extract a portion of the tuple using the syntax start_index:end_index.
- The start_index is inclusive, meaning the element at that index is included in the slice.
- The end_index is exclusive, meaning the element at that index is not included in the slice.
Example:
my_tuple1 = ('a','b',7,3,6)
print(my_tuple1[1:4])
print(my_tuple1[:3])
print(my_tuple1[2:])
Output:
Indexing tuples
Indexing allows you to access individual elements within a tuple using their respective indices. Let me explain with an
Example:
my_tuple1 = ('apple','banana','cherry','date','elderberry')
print(my_tuple1[2])
Output:
Here, to access the third element, which is cherry, we have used my_tuple1[2]:
Positive and negative indexing
Positive indexing starts from 0 for the first element, while negative indexing starts from -1 for the last detail. Let me explain with an.
Example:
my_tuple1 = ('apple','banana','cherry','date','elderberry')
print(my_tuple1[1])
Output:
In this example, my_tuple[1] returns the element at index 1, which is ‘banana’.
We can use negative indexing to access elements from the end of the tuple. The index -1 mentions the last element, -2 represents the second-to-last element, and so on. For standard, to contact the last element ‘elderberry’, we can use my_tuple[-1]:
Code:
my_tuple1 = ('apple','banana','cherry','date','elderberry')
print(my_tuple1[-1])
Output:
In this case, my_tuple1[-1] returns the last element of the tuple.
Remember that indexing a tuple yields a single element, not a tuple. In our code, you may thus use the indexed element directly or assign it to a variable.
Since an index is longer than a tuple, an error message will occur if we try to access one outside its permitted range, like my_tuple1[5].
Updating Tuples
Tuples are immutable, which implies that once a tuple is constructed, its elements cannot be changed. To update tuples indirectly, there are a couple of solutions. Let’s look at these approaches:
Example:
my_tuple1 = ('apple', 'banana', 'cherry', 2)
my_list1 = list(my_tuple1) # convert a tuple to list
my_list1[1] = 'date' # update the element at index 1
new_tuple1 = tuple(my_list1) # convert list back to tuple
print(new_tuple1)
Output:
Delete Tuple Elements
To delete a tuple Element, we can use the del keyword. Let’s go and explore this further:
Example:
my_tuple1 = ('apple', 'banana', 'cherry', 'elderberry')
my_list1 = list(my_tuple1) # convert a tuple to list
del my_list1[1] # Delete the element at index 1
# my_list1[1] just accesses the element, it does not delete it
new_tuple1 = tuple(my_list1) # convert list back to tuple
print(new_tuple1)
Output:
The above example, the tuple my_tuple is changed to a list using list(my_tuple). The element at index 1 (‘banana’) is deleted using del my_list[1]. Lastly, the modified list is transferred back to a tuple using a tuple(my_list), resulting in the tuple new_tuple without the deleted element.
It’s important to note that deleting elements from a tuple indirectly by converting it to a list and back to a tuple creates new objects, as tuples are immutable.
Modifying Tuples
Tuples have an immutable nature, which means that once a tuple is created, its elements cannot be changed directly. However, there are a few ways to modify tuples indirectly:
Immutable nature of tuples
Tuples are immutable, meaning their elements cannot be modified. If we try to change an element in a tuple, it will result in an error.
Example:
my_tuple1 = (1,2,3)
tuple[1]=10 #This will raise an error
Output:
Reassigning variables referencing tuples
Although we cannot modify the elements of a tuple, we can reassign variables referencing tuples to create a new tuple.
Example:
my_tuple1 = (1,2,3)
my_tuple2= my_tuple1
print(my_tuple2)
Output:
Converting tuples to lists and vice versa
Tuples can be converted to lists, modified, and then converted back to tuples. This allows for more flexibility in modifying tuple elements.
Example:
my_tuple1 = (1,2,3)
list1 = list(my_tuple1) # converting tuple to list
list1[1] = 10 # modifying the list
my_tuple1 = tuple(list1) #convert to tuple
print(my_tuple1)
Output:
Tuple Operations and Methods
Below are the different operations and methods:
Tuple concatenation and repetition
You can concatenate tuples using the ‘+’ operator to create a new tuple that combines the elements of multiple tuples.
Example:
tuple1 = (1,2,3)
tuple2 = (4,5,6)
new_tuple = tuple1+tuple2
print(new_tuple)
Output:
Tuple membership
Using the ‘ in ‘ operator, we can check if an element is present in a tuple. It returns True if the element is found and False if not.
Example:
tuple1 = (1,2,3,4,5)
print(3 in tuple1)
print(6 in tuple1)
Output:
Tuple length, minimum, and maximum
Lenght: ‘len()’ function can be used to invent the length of a tuple, which is the number of elements it contains.
Example:
tuple1 = (1, 2, 3, 4, 5)
print(len(tuple1))
Output:
Minimum value: To find the smallest value in a tuple, we can utilize the min() function.
tuple2 = (6, 5, 3, 7)
print(min(tuple2))
Output:
Maximum value: We can use the max() function to find the largest value in a tuple.
tuple2 = (6, 5, 3, 7)
print(max(tuple2))
Output:
Both min() and max() can take a key function as an argument to compare elements based on a specific attribute.
For example,
To find the minimum based on the length of string elements:
tuple3 = ('abc', 'xy', 'def', 'ijk')
print(min(tuple3, key=len))
Output:
Counting and finding elements in tuples
To determine the number of times a particular element appears in a tuple, you can utilize the ‘count()’ method.
Example:
tuple1 = (1,2,2,3,4,5,4)
print(tuple1.count(2))
print(tuple1.count(4))
Output
You can use the ‘index()’ method to locate the position of the first instance of a particular element in a tuple.
Example:
tuple1 = (1,2,3,4,5)
print(tuple1.index(3))
print(tuple1.index(6))
Output:
Iterating over Tuples
Using loops to iterate over tuples
We can use loops, such as the ‘for’ loop, to repeat over the elements of a tuple one by one.
Example:
tuple1 = (5,7,2,8,3)
for element in tuple1:
print(element)
Output:
Unpacking tuples in loops
Unpacking tuples in loops enables us to assign each tuple element to a separate variable during iteration.
Example:
tuple1 = (1,2,3)
for a, b, c in (tuple1,):
print(a, b, c)
Output:
Enumerating tuples
You can use the ‘enumerate()’ function to iterate over a tuple and simultaneously obtain the index and value of each element.
Example:
tuple1 = (10,20,30,40,50)
for index,value in enumerate(tuple1):
print(index,value)
Output:
Tuple Packing and Unpacking with Examples
Packing multiple values into a tuple
Tuple packing refers to combining multiple values into a single tuple. To accomplish this, you can separate the values with commas.
Example:
name = "Sam"
age = 34
country = "America"
person_tuple = (name, age, country) # Added parentheses
print(person_tuple)
Output:
Unpacking tuples into individual variables
Tuple unpacking allows us to assign the elements of a tuple to individual variables. The number of variables must match the number of elements in the tuple.
Example:
person_tuple = ("John",45,"USA")
name , age , country = person_tuple
print(name)
print(age)
print(country)
Output:
Unpacking with the star (*) operator
You can use the star () operator to unpack a variable number of elements from a tuple into individual variables. It is useful when the number of elements in the tuple is unknown or can vary.
Example:
numbers_tuple = (1,2,3,4,5)
first , *middle , last = numbers_tuple
print(first)
print(middle)
print(last)
Output:
Tuple Comprehensions
Creating tuples using comprehensions
We can use tuple comprehensions to create tuples based on certain conditions or calculations. The syntax comprises defining an expression, followed by a “for” loop and optional “if” conditions
Example:
numbers = (1,2,3,4,5)
squared_numbers = tuple(x ** 2 for x in numbers)
# Added the 'in numbers' to specify the iterable
print(squared_numbers)
Output:
Filtering and transforming elements in tuples
Tuple comprehensions can filter elements from an existing tuple based on certain conditions or transform the elements using expressions.
Example:
numbers = (6, 3, 7, 8, 2)
even_squared_numbers = tuple(x**2 for x in numbers if x % 2 == 0)
print(even_squared_numbers)
Output:
Practical Applications of Tuples
Using tuples as keys in dictionaries
We can use tuples as keys in dictionaries because they are immutable. This is useful when we need to create a dictionary with composite keys that consist of multiple values.
Example:
student_grades = {("Jorge","Jorge"): 85, ("Liam","Joseph"):92}
print(student_grades[("Jorge","Jorge")])
Output:
Returning multiple values from functions
Functions often use tuples to return multiple values. Instead of returning individual values, we can pack them into a tuple and unpack them at the caller’s end.
Example:
def get_user_info():
name = "Jessica"
age = 33
email = "[email protected]"
return name, age, email
# Call the function and store the returned values in variables
user_name, user_age, user_email = get_user_info()
# Print the returned values
print("Name:", user_name)
print("Age:", user_age)
print("Email:", user_email)
Output:
Working with functions that accept variable-length arguments
Tuples are useful when working with functions that accept variable-length arguments. We can pass a tuple of values to such functions, and they can handle various arguments.
Example:
def calculate_average(*numbers):
total =sum(numbers)
average = total / len(numbers)
return average
avg = calculate_average(6,2,7,9,3)
print(avg)
Output:
Tuple Best Practices and Tips
Conclusion
Python has ordered collections of elements called tuples that do not allow modification once created. They serve as a useful way to group related data, similar to lists. Tuples are often useful when data security or integrity is of utmost importance because their immutability ensures that data remains unchanged. People commonly use them to represent fixed sets of values or use them as keys in dictionaries. Additionally, tuples offer efficient indexing and unpacking capabilities, making them versatile data structures in Python.
Recommended Article
We hope that this EDUCBA information on “Tuples in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.