Table of Contents
A tuple is an ordered, immutable collection of items.
That means:
- Ordered: The elements have a defined order that won’t change.
- Immutable: Once created, you cannot modify (add, remove or change) its elements.
- You create a tuple using parentheses (), separated by commas.
- Use tuples for static data and lists for dynamic data.
Consider an example below.
fruits = ("apple", "banana", "cherry")
print(fruits)
# Output
# ('apple', 'banana', 'cherry')
Creating Tuples in Different Ways
There are different ways to create a tuple.
- Tuple constructor()
- Tuple without Parenthesis
Let’s take a look at them one by one.
# Empty tuple
empty_tuple = ()
# Single-element tuple
single = ("hello",)
# Tuple from a list
nums = tuple([1, 2, 3])
# Tuple without parentheses
colors = "red", "green", "blue"
empty_tuple = (): Creates a tuple with zero elements, defined by empty parentheses.
single = (“hello”,): Creates a tuple with exactly one item. The trailing comma (,) is mandatory without it, Python treats the parentheses as a grouping expression for a single variable.
nums = tuple([1, 2, 3]): Uses the built-in tuple() constructor to convert any iterable object (like a list, string, or set) into a new immutable tuple.
colors = “red”, “green”, “blue”: Creates a tuple without using parentheses. Python automatically recognizes the comma-separated sequence as a tuple.
Accessing Tuple Elements and Tuple Slicing
Accessing tuple elements is done using indexing (square brackets [ ]), which retrieves a specific item based on its position within the tuple.
data = ("apple", "kiwi", "cherry", "grape", "banana")
print(f"Original Tuple: {data}")
print(f"data[0]: {data[0]}")
print(f"data[-2]: {data[-2]}")
print(f"data[1:4]: {data[1:4]}")
print(f"data[2:]: {data[2:]}")
print(f"data[:2]: {data[:2]}")
# Output
# Original Tuple: ('apple', 'kiwi', 'cherry', 'grape', 'banana')
# data[0]: apple
# data[-2]: grape
# data[1:4]: ('kiwi', 'cherry', 'grape')
# data[2:]: ('cherry', 'grape', 'banana')
# data[:2]: ('apple', 'kiwi')
The above code demonstrates accessing tuple elements and tuple slicing.
1. Positive Indexing: Accesses the element by counting forward from the start, (0 is the first item).
data[0]: accesses the first element from the tuple
2. Negative Indexing: Accesses the element by counting backward from the end -1 is the last item.
data[-1]: Accesses the element from the last(-1 selects the last element).
3. Tuple Slicing: We can access a custom range of tuple elements.
data[1:4]: it gives elements starting from the first element and stops before the fourth.
data[2:]: It extracts elements starting from index two and continues till the last element.
data[:2] : This will extract the elements starting from the first element and stop before the element with index two.
Tuple Packing and Unpacking
person = ("Jonny", 25, "Engineer")
name, age, profession = person
print(name) # Alice
print(age) # 25
print(profession) # Engineer 'Code is Poetry' );
The above code demonstrates Tuple Packing and Unpacking (or sequence unpacking), a powerful feature in Python that simplifies variable assignment.
Packing (Creation):
person = ("Jonny", 25, "Engineer"):
A single tuple object is created, containing three elements (a string, an integer, and a string). This is called Tuple Packing. Tuple packing is the process of automatically combining multiple values into a single tuple.
Unpacking (Assignment):
name, age, profession: This is Tuple Unpacking. The elements from the person tuple are assigned sequentially to the three new variables on the left side of the equals sign.
Tuple Function and Methods
Tuple currently has 2 Methods
- index()
- count()
other functions include
- len()
- max()
- min()
- sum()
- sort()
| Function | Description |
|---|---|
| len() | Returns number of elements |
| max() | Returns largest item |
| min() | Returns smallest item |
| sum() | Adds up numeric elements |
| count() | Counts occurrences |
| index() | Returns index of item |
| sorted() | returns a sorted list of all items in a tuple |
scores = (10, 50, 40, 30, 90, 40)
print(f"Original Tuple: {scores}")
# 1. len()
length = len(scores)
print(f"1. Length: {length}")
# 2. max()
maximum = max(scores)
print(f"2. Maximum: {maximum}")
# 3. min()
minimum = min(scores)
print(f"3. Minimum: {minimum}")
# 4. sum()
total = sum(scores)
print(f"4. Total Sum: {total}")
# 5. count()
count_40 = scores.count(40)
print(f"5. Count of 40: {count_40}")
# 6. index()
index_50 = scores.index(50)
print(f"6. Index of 50: {index_50}")
# 7. sorted()
sorted_list = sorted(scores)
print(f"7. Sorted List: {sorted_list}")
# Output
# Original Tuple: (10, 50, 40, 30, 90, 40)
# 1. Length: 6
# 2. Maximum: 90
# 3. Minimum: 10
# 4. Total Sum: 260
# 5. Count of 40: 2
# 6. Index of 50: 1
# 7. Sorted List: [10, 30, 40, 40, 50, 90]
Deleting a Tuple
Tuples are immutable and hence individual characters of the tuple cannot be deleted. We have to delete the entire tuple itself. We can use the del keyword to delete the tuple.
tuple = (0,1,2,3,4,5,6)
del tuple
print(tuple)
# Traceback (mostrecent call last):
# File "", line 3, in
# NameError: name 'tuple' is not defined
Why Tuples Are Immutable (And Why It Matters)
Immutability makes tuples:
- Hashable→ usable as dictionary keys
- Thread-safe→ can be shared safely between threads
- Performance-friendly→ faster to process than lists
When to Use Tuples: Use tuples when:
Data should not change.
You want faster performance.
You need to use the collection as a dictionary key.
You’re dealing with fixed records like coordinates, days of the week or database rows.
Looping through a Tuple
Looping through a tuple involves involves iterating over every element in a tuple sequentially, allowing you to access and perform an action on each item individually.
colors = ("red", "green", "blue", "yellow")
print(f"Tuple: {colors}")
# 1. Simple Iteration
for color in colors:
print(color)
# 2. Index Iteration
print("\n2. Index Loop ")
for i in range(len(colors)):
print(f"Index {i}: {colors[i]}")
# Output
# Tuple: ('red', 'green', 'blue', 'yellow')
# red
# green
# blue
# yellow
# 2. Index Loop
# Index 0: red
# Index 1: green
# Index 2: blue
# Index 3: yellow
Tuple Concatenation and Multiplication
Tuple Concatenation
Tuple Joining is the process of combining two or more existing tuples to create a single new tuple using the + operator.
new_tuple = tuple1 + tuple2
Tuple multiplication
uses the * operator to repeat the elements of a tuple a specified number of times to create a new tuple.
repeated_tuple = tuple * integer
tuple1 = (1, 2, 3)
tuple2 = (“A”, “B”)
Consider the above tuples and write a Python program to concatenate the tuples and then perform tuple multiplication on the concatenated tuples
tuple1 = (1, 2, 3)
tuple2 = ("A", "B")
print(f"Tuple 1: {tuple1}")
print(f"Tuple 2: {tuple2}")
# 1. Tuple Joining (+)
joined_tuple = tuple1 + tuple2
print(f"1. Concatenation: {joined_tuple}")
# 2. Tuple Multiplication (*)
repeated_tuple = tuple2 * 3
print(f"2. Multiplication: {repeated_tuple}")
# output
# Tuple 1: (1, 2, 3)
# Tuple 2: ('A', 'B')
# 1. Concatenation: (1, 2, 3, 'A', 'B')
# 2. Multiplication: ('A', 'B', 'A', 'B', 'A', 'B')
FAQ (Frequently Asked Questions)
1. What is a Python Tuple?
A Python tuple is an ordered, immutable collection of elements. It can store multiple items such as strings, numbers or even other tuples in a single variable. Tuples are created by using parentheses and their elements are separated by commas.
Example:
my_tuple = (“apple”, “banana”, “cherry”)
print(my_tuple)
2. What is the difference between a List and a Tuple in Python?
The differences are given below
| Features | List | Tuple |
|---|---|---|
| Syntax | [ ] | ( ) |
| Mutability | Mutable | Immutable |
| Speed | Slower | Faster |
| Hashable | No | Yes |
| Memory Usage | More | Less |
3. How to convert a List into a Tuple in Python?
A list can be converted to a tuple by using a tuple() constructor.
Example:
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple) # (1, 2, 3, 4)
4. What is Tuple Comprehension in Python?
There is no tuple comprehension in Python. However you can create tuples using generator expressions inside the tuple() function.
my_tuple = tuple(x**2 for x in range(5))
print(my_tuple)
# (0, 1, 4, 9, 16)
5. How to sort a List of Tuples in Python?
You can use the sorted() function or list.sort() method to sort a list of tuples.
data = [(3, ‘c’), (1, ‘a’), (2, ‘b’)]
sorted_data = sorted(data)
print(sorted_data)
# [(1, ‘a’), (2, ‘b’), (3, ‘c’)]
6. Is a Tuple Mutable in Python?
No, tuples are immutable. Once a tuple is created, the elements cannot be removed or added.
7. What is the Difference Between a Tuple and a Dictionary in Python?
| Features | Tuple | Dictionary |
|---|---|---|
| Syntax | ( ) | { } |
| Type | Ordered Sequence | Key- Value Pair |
| Mutability | Immutable | Mutable |
| Access Method | Index-Method | Key-Based |
| Use Case | Fixed Data Collection | Dynamic Data Mapping |
8. How to Add Elements in a Tuple in Python?
An element cannot be added directly to a tuple because it is immutable. But you can create a new tuple by concatenating an existing one with another tuple.
Example:
# (1, 2, 3, 4)
9. What are the Tuple Methods in Python?
There are two methods.
index(): Returns the index of the first occurrence of a value.
count(): Returns the number of occurrences of a value.