04
JulTuples in Python with Examples - A Beginner Guide
Python tuples are ordered, immutable collections of items. Tuples are similar to lists in Python; the only difference is that tuples are immutable. Once a tuple is created, its values cannot be changed or updated, ensuring data integrity. Real use cases of tuples are storing bank account numbers, user IDs, color codes, etc.
What are Tuples in Python?
- Tuples are ordered collections of elements, similar to Python lists, but they are immutable.
- This implies that once a tuple has been created, it cannot be altered.Parentheses() are used to define tuples, while commas are used to separate the elements.
- They help store data that should not be modified, such as constants or sets of related data.
- There are various concepts related to tables, such as tuple datatypes, methods, and operations. Let's see one by one
Example:
my_tuple=(1,2,3,4,5)
my_tuple1=(1,’ScholarHat’)
print(my_tuple)
print(my_tuple1)
1. Python Tuple Data Type
>>> blue= (0, 0, 255)
After blue has been defined, there is no need to modify or add any further elements. Why? Your variable name will be misleading if you alter the value of even one component, as you will no longer have a pure blue color. Your color won't be an RGB color if you add a new component. Therefore, tuples are ideal for representing this kind of data.
2. Characteristics of Tuple
- Ordered: The elements are grouped sequentially based on the order in which they were inserted.
- Lightweight: In comparison to other sequences like lists, they need very little memory.
- Zero-based indexable: You can retrieve their elements using integer indices that begin at zero.
- Immutable: They are resistant to alterations or in-place mutations to the elements they contain. They don't encourage operations to expand or contract.
- Heterogeneous: They are capable of holding changeable objects as well as objects with a variety of data types and domains.
- Nestable: You can have tuples of tuples since they can hold other tuples.
- Iterable: You can work with each of their elements by performing operations on them using a loop or comprehension, as they allow for iteration.
- Sliceable: You can extract a number of elements from a tuple because they allow slicing operations.
- Combinable: They can be used to combine two or more tuples using concatenation operators to create a new tuple because they support concatenation operations.
- Hashable: When every tuple item in a dictionary is unchangeable, they can function as keys.
3. Tuple Objects
>>> record = ("Sourav", 25, "SEO Manager")
>>> record
('Sourav', 25, 'SEO Manager')
This tuple's elements are objects of various data types that each represent a record of information from a database table. Accessing the tuple object will reveal that the data pieces maintain their original sequence of insertion. Throughout the tuple's existence, this order doesn't change.Within a tuple, you can retrieve specific objects using their index or position. Each of these indices begins at zero:
>>> record[0]
'Sourav'
>>> record[1]
25
>>> record[2]
'SEO Manager'
How to Create Tuples in Python?
In Python, there are multiple methods for creating a tuple.
They are listed in the following order:
- By using Parentheses()
- With just one item
- Tuple Constructor
Read More - 50 Python Interview Questions
1. By using Parentheses()
Python uses parentheses () to define tuples. Commas are used to separate the elements inside the brackets.Example of Creating a Tuple in Python using Parenthesis()
scholarhat_articles = ("C", "C++", "Python", "Java")
print(scholarhat_articles)
Explanation:
The tuple scholarhat_articles is defined in this code in the Python Compiler, which is then printed. Four strings ("C", "C++", "Python", and "Java") that relate to articles about programming languages are stored in the tuple.
Output
('C', 'C++', 'Python', 'Java')
2. With just one item
In Python, a comma must be added after the element to create a tuple with just that one element. It will be understood as a string type otherwise.
Example of Creating Tuple in Python using just one item
favorite_color = ("blue",)
print(f"My favorite color is: {favorite_color[0]}")
Explanation:
With a comma, this code generates a tuple called favorite_color that has the sole element "blue" in it. Prints a description along with the element (which is "blue") at index 0.
Output
My favorite color is: blue
Read More - Python Developer Salary in India
3. Tuple Constructor
You can construct tuple objects in Python from many data structures by using the tuple constructor. It is essentially an inbuilt function in Python that accepts an iterable as input and outputs a tuple with all its elements.Example of Creating a Tuple in Python using the Tuple Constructor
my_list = ["apple", "banana", "cherry"]
my_tuple = tuple(my_list)
print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")
Explanation:
This code in the Python Online Editor generates a list of fruits with the names "apple," "banana," and "cherry" that it calls my_list.Using the tuple() constructor creates a tuple named my_tuple from the list. It uses strings toprint the list and the tuple along with relevant messages.
Output
List: ['apple', 'banana', 'cherry']
Tuple: ('apple', 'banana', 'cherry')
Tuple vs list in Python:
Feature | Tuple | List |
Mutability | Immutable (cannot be changed after creation) | Mutable (can be changed after creation) |
Syntax | () (e.g., my_tuple = (1, 2, 3)) | [] (e.g., my_list = [1, 2, 3]) |
Performance | Faster (due to immutability and fixed size) | Slower (overhead for dynamic resizing) |
Use cases | Fixed or constant data (e.g., coordinates, settings) | Dynamic data that may change (e.g., items in a cart) |
Hashable | Yes, if all elements are hashable (can be used as dict keys) | No, lists are unhashable and cannot be used as dict keys |
Example | Database records, function returns | Collections of items to modify or iterate over |
Built-in Functions for Tuples
Python provides various built-in functions for doing operations with tuples
1. len(tuple): len() method returns the length of the tuple
t = (1, 2, 3)
print(len(t))
Output: 5
2.max(tuple): The max() method returns the value of the maximum item in the tuple
t = (1, 5, 3)
print(max(t))
Output: 5
3.min(tuple): The min() method returns the value of the minimum item in the tuple
t = (1, 5, 3)
print(min(t))
Output: 1
4.sum(tuple): The sum() method returns the sum of all items in the tuple
t = (1, 2, 3)
print(sum(t))
Output: 6
5.any(tuple): any() method returns the if any item in the tuple is true
t = (0, False, 3)
print(any(t))
Output: True (because of 3)
6.all(tuple): all() method returns true if all items in the tuple are true
t = (0, False, 3)
print(all(t))
Output: False
Tuple Operations in Python with Examples
1. How to Access Tuple Elements in Python
Accessing items in a tuple in Python is done using indexing, similar to lists. Tuples are ordered sequences, and each item has a numerical index starting from 0 for the first item. You can use these indices within square brackets to retrieve specific elements.Example of Accessing Tuple Elements in Python
my_tuple=(1,2,3,4)
print(my_tuple[0],end=" ") #print first item (positive indexing)
print(my_tuple[-1]) #print last item (negative indexing)
Explanation:
- my_tuple[0] accesses the first item of the tuple (1) using positive indexing.
- my_tuple[-1] accesses the last item of the tuple (4) using negative indexing.
Output
1 4
2. Slicing in Tuple
Example of Updating Tuples in Python
my_tuple=(1,2,3,4)
print(my_tuple[0:3],end=" ") #print item 1,2,3
print(my_tuple[1:3]) #print item 2,3
Explanation:
- my_tuple[0:3] slices the tuple from index 0 to 2 (last index is exclusive), returning (1, 2, 3).
- my_tuple[1:3] slices from index 1 to 2, returning (2, 3).
Output
123 23
3. Unpacking the value of a tuple
Example of unpacking the value of a tuple in Python Editor
my_tuple=(1,2,3,4)
a,b,c,d = my_tuple
print(a,end=" ") # print 1
print(b,end=" ") # print 2
print(c,end=" ") # print 3
print(d,end=" ") # print 4
Explanation:
- Each element in my_tuple is assigned to a separate variable:
- a = 1, b = 2, c = 3, d = 4.
Output
1 2 3 4
4. Concatenation of a tuple
Example of concatenation a tuple in Python Editor
my_tuple1=(1,2,3)
my_tuple2=(4,5,6)
my_tuple3=my_tuple1+my_tuple2
print(my_tuple3) #print 1,2,3,4,5,6
Explanation:
- The + operator joins the two tuples into a new one:
- (1, 2, 3) + (4, 5, 6) → (1, 2, 3, 4, 5, 6).
Output
1,2,3,4,5,6
3. Deleting a tuple in Python
Example of unpacking the value of a tuple in Python Editor
my_tuple=(1,2,3)
del my_tuple
Explanation:
- The del keyword deletes the entire tuple from memory.
- After this, using my_tuple will raise an error as it no longer exists.
Output
1 2 3 4
Practical Use Cases
x, y = 10, 20
x, y = y, x # Swaps the values
print(x, y) # Output: 20 10
def get_point():
return 1, 2
x, y = get_point()
print(x, y) # Output: 1 2
These concepts make Python code more readable and efficient, especially when working with multiple values.
These concepts could improve the readability and effectiveness of Python code, particularly when handling many values.
4. Returning Tuples From Functions
Python practices frequently return tuples, especially when you wish the function to return numerous values. Tuples are a great option for returning a set of related data because they may hold several immutable elements.
Basic Example
def get_coordinates():
x = 10
y = 20
return x, y # Returns a tuple (10, 20)
coordinates = get_coordinates()
print(coordinates) # Output: (10, 20)
Unpacking Returned Tuples
def get_coordinates():
x = 10
y = 20
return x, y # Returns a tuple (10, 20)
x, y = get_coordinates()
print(x) # Output: 10
print(y) # Output: 20
Returning Multiple Values
Returning a tuple is handy when a function needs to return multiple values of different types:
def analyze_data(data):
mean = sum(data) / len(data)
minimum = min(data)
maximum = max(data)
return mean, minimum, maximum # Returns a tuple (mean, min, max)
data = [4, 8, 15, 16, 23, 42]
mean, minimum, maximum = analyze_data(data)
print("Mean:", mean) # Output: Mean: 18.0
print("Minimum:", minimum) # Output: Minimum: 4
print("Maximum:", maximum) # Output: Maximum: 42
def process_args(*args):
return args # Returns a tuple of all arguments
result = process_args(1, 2, 3, "Python", True)
print(result) # Output: (1, 2, 3, 'Python', True)
Realistic Use Cases
- Multiple Results: Functions that do calculations and provide a number of related results.
- Efficient Data managing: Combining several return values into a tuple to make managing them easier.
- Data Transformation: Data transformation refers to operations, including unit conversions and coordinate conversions, that require the return of altered data in pairs.
5. Creating Copies of a Tuple: Using the Copy Module
import copy
original_tuple = (1, 2, 3)
copied_tuple = copy.copy(original_tuple)
print(copied_tuple) # Output: (1, 2, 3)
Output
(1, 2, 3)
6. Concatenating and Repeating Tuples
1. Concatenating Tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple) # Output: (1, 2, 3, 4, 5, 6)
Output
(1, 2, 3, 4, 5, 6)
2. Repeating Tuples
The * operator repeats a tuple a given number of times, which is useful for repeating its elements.tuple1 = (1, 2, 3)
repeated_tuple = tuple1 * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Output
(1, 2, 3, 1, 2, 3, 1, 2, 3)
Summary
FAQs
Take our Python skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.