Tuples in Python are similar to lists but they cannot be changed. This makes them useful in certain situations. The immutability of tuples makes them ideal for certain tasks and scenarios. We will explore many ways in which tuples can be used in Python programming.
Related: Tuple Methods with Examples
This article will give you a better understanding of the Python Tuple data structure. You will learn what is tuple, how they are different from lists, and how they can be used in a variety of applications.
Table of contents
1. What is a Tuple in Python?
Python Tuple is an ordered collection of items that can contain elements of any data type, including other tuples. Unlike the Python List, The elements of Tuple, cannot be modified once created.
The immutability of Tuple makes them safer to use in certain situations where data integrity is important. The advantage of using tuples is their memory efficiency. Because tuples are immutable, they can be stored in a single block of memory.
1.1 Example of Tuple in Python
See the below Python examples of creating a tuple using numbers and mixed data types:
# Create a tuple of numbers
my_tuple = (1, 2, 3, 4)
print(my_tuple)
# Create a tuple of mixed datatypes
my_tuple = (1, 'Hello', (1,2,3))
print(my_tuple)
1.2 Key Points of Tuple
Key Points of Tuple | Explanation |
---|---|
Immutable | Once a tuple is created, its elements cannot be modified. |
Ordered Collection | A tuple is an ordered collection of items, meaning the items are stored in a specific order and can be accessed by their index. |
Parenthesis | A tuple is represented by a sequence of values separated by commas, enclosed in parentheses. |
Memory Efficient | Tuples are stored in a single block of memory, which makes them more memory efficient than lists. |
Built-in Methods | Tuples have several built-in methods that can be used for common operations like counting the number of occurrences of an element, finding the index of an element, etc. |
Tuple Unpacking | Tuples can be used for multiple assignments in a single line, which is known as tuple unpacking. |
Use as Key in Dictionary | Tuples can be used as keys in a dictionary, which uses the hash value of the key to retrieve the corresponding value. |
2. Create a Tuple in Python
There are several different ways to create a tuple in Python. The most common is to use round brackets () to enclose a comma-separated list of elements. See the following different ways of creating a Tuple in Python:
2.1 tuple() – Create a Tuple
The tuple() constructor is a built-in Python function that creates a tuple from an iterable. An iterable is any Python object that can be looped over, such as a list, string, or range.
When the tuple() constructor is called with an iterable, it returns a new tuple containing the items from the iterable. The items in the tuple will be in the same order as they appear in the iterable.
Example: Create an empty tuple, using the “tuple()” constructor with no arguments
# Create tupe using constructor
my_tuple = tuple()
data_type = type(my_tuple)
print(data_type)
# Output:
# class 'tuple'
Example: Create a tuple with items, using the “tuple()” constructor with the items as arguments:
# Creat tuple by taking list as argument
my_tuple = tuple([1, 2, 3])
print(my_tuple)
# Output:
# (1, 2, 3)
The tuple()
constructor takes one optional argument. The arguments must be iterable, like a list or a string.
2.2 Use Round Parentheses
To create a tuple using round parentheses, you simply enclose a comma-separated list of elements inside round brackets.
For example, the following creates a tuple with three elements:
# Example 1:
my_tuple = (1, 2, 3)
# Example 2:
a = 1
b = 2
c = 3
my_tuple = (a, b, c)
# Example 3:
my_tuple = (1,)
2.3 Create a Nested Tuple
A nested tuple is a tuple that contains one or more tuples as its elements. To create a nested tuple, you can include a tuple as an element within another tuple.
# Example 1
my_tuple = (1, ("python", "java"))
# Example 2
my_tuple = (1, (2, (3, 4)))
3. Accessing Elements from Tuple
Accessing elements in a tuple is similar to accessing elements in a list. You can use the index of an element to access it. The index of the first element is 0, the index of the second element is 1, and so on.
You can also use negative indexing to access elements from the end of the tuple. For example, the following code accesses the last element of a tuple:
# Create tuple
my_tuple = ('Python', 'Java', 'C++', 'JavaScript')
# Access tuple element
first_language = my_tuple[0]
print(first_language) # Output: 'Python'
last_language = my_tuple[-1]
print(last_language)
# Output:
# 'JavaScript'
3.1 Slicing to Access a Range of Elements
You can also use slicing to access a range of elements in a tuple. For example, the following code accesses the second and third elements of a tuple:
# Slice tuple
first_two_languages = my_tuple[:2]
print(first_two_languages)
# Output:
# ('Python', 'Java')
3.2 Access the Elements of a Nested Tuples
To access the elements of a nested tuple, you can use multiple indices to access elements at different levels of nesting. It is the same as accessing the element of the nested list.
# Creates a nested tuple with elements
my_tuple = ('Python', ('Java', 'C++'), ('JavaScript', ('Scala', 'Kotlin')))
# Accesses the first element of the tuple
first_element = my_tuple[0]
# Accesses the first element of the second tuple
second_element = my_tuple[1][0]
# Accesses the first element of the third tuple
third_element = my_tuple[2][1][0]
4. Different Data Types Allowed in a Tuple
A tuple can contain an integer, a string, a list, a float, or any other datatype. There is no restriction on elements inside a Tuple in Python.
# Example 1: Tuple with integers and strings
my_tuple = (1, 2, 3, 'hello', 'world')
# Example 2: Tuple with a mix of data types
my_tuple = (1, 'hello', [1, 2, 3], 3.14, (1, 2))
# Example 3: Tuple with a boolean and None
my_tuple = (True, None)
# Example 4: Tuple with a set and a dictionary
my_tuple = ({"name": "Alex", "age": 25}, {1, 2, 3})
5. Perform for Loop on a Tuple
You can use a for loop to iterate over the elements of a tuple in Python. This is same as if you are iterating over some other iterable, like list, set, or range.
5.1 Syntax of for Loop on a Tuple
# Syntax
for element in my_tuple:
# Do something with element
5.2 Example of for loop on a Tuple
# Example of tuple with for loop
my_tuple = ('Python', 'Java', 'C++', 'JavaScript')
for element in my_tuple:
print(element)
# Output:
# Python
# Java
# C++
# JavaScript
5.3 enumerate() and FOR Loop on a Tuple
Use the enumerate()
function in combination with a for
loop to iterate over the elements of a tuple in Python while also keeping track of the index of each element.
# Using enum
for index, element in enumerate(my_tuple):
print(index, element)
# 0 Python
# 1 Java
# 2 C++
# 3 JavaScript
6. Remove of Add Elements to Tuple
As a Python tuple is an immutable data structure, you cannot add or remove elements from an existing tuple. If you need to add or remove elements, you will have to create a new tuple with the desired elements.
Adding an element to a tuple can be done by concatenating the new element with the existing tuple using the +
operator, or by using the tuple()
function to convert a list with the new elements into a tuple.
# Add element using + operator
new_tuple = my_tuple + ('Kotlin')
# Remove Elements using Slicing
new_tuple = my_tuple[:2] + my_tuple[3:]
7. Tuple Usecases in Python
When to Use Tuple? Tuples are a useful data structure in Python for a number of reasons, here are a few use cases where tuples are particularly useful:
7.1 Using Tuples as a Return Value
With tuples, you can return multiple values from a function. Functions in Python can only return one value, but sometimes it is useful to return multiple values.
# Create function that returns muliple values
def divide(a, b):
if b == 0:
return (False, "Cannot divide by zero")
else:
return (True, a / b)
success, result = divide(5, 2)
if success:
print(result)
else:
print(result)
7.2 Unpacking Values
# Unpacking values
my_tuple = (1, 'hello', [1, 2, 3])
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 'hello'
print(c) # Output: [1, 2, 3]
7.3 Python Tuple Performance
Python Tuples are generally faster than lists because they are immutable and do not require additional memory for modification operations.
When you perform an operation on a list, such as adding or removing an element, a new list is created in memory with the updated elements. This can be a relatively slow process, especially if the list is large.
When you perform an operation on a tuple, no new tuple is created in memory. This is because a tuple is immutable, meaning that its elements cannot be modified after it is created.
import timeit
# Generate a large list
my_list = list(range(100000))
# Generate a large tuple
my_tuple = tuple(range(100000))
# Measure the time it takes to add an element to the list
list_time = timeit.timeit(lambda: my_list + [1], number=10000)
# Measure the time it takes to add an element to the tuple
tuple_time = timeit.timeit(lambda: my_tuple + (1,), number=10000)
print(f"Time to add an element to a list: {list_time}")
print(f"Time to add an element to a tuple: {tuple_time}")
Yields the following output:
# Output:
Time to add an element to a list: 36.548752599999716
Time to add an element to a tuple: 21.531841000003624
If you are working with large data sets or in performance-critical applications, using tuples can lead to better performance. But, if you need to add, remove or modify elements frequently, it’s better to use lists.
8. Python Tuple Examples
Following are the important examples of tuples you should know when working in Python.
- Python Tuple Unpacking with Examples
- Python Tuple Access with Example
- Add Element to Tuple in Python
- Add Elements of Tuples in Python
- Append Element to a Tuple in Python
- Python Empty Tuple with Examples
- Python Tuple Slice with Examples
- Python Tuple Length with Example
- How to Sort List of Tuples in Python
- Convert Tuple to String in Python
- Convert String to List of Tuples in Python
- Convert String Tuples to List Tuples Python
- Convert Tuple to List in Python
- Convert List to Tuple in Python
- Convert Tuples to Dictionary in Python
- Flatten List of Tuples to String in Python
- Convert List of Tuples into List in Python
- Convert List of Lists to Tuple of Tuples in Python
9. Conclusion
In this article, we have explained Tuples in Python and how to work with them. We have also learned the use cases for tuples. Along that we have also learned nested tuples and how to access the elements of the nested loops. If you have any questions please let me know in the comment section.