Tuples in Python
Tuples are one of the most important built-in data types in Python. They are similar to lists but with one major difference:
- Tuples are immutable (cannot be changed after creation)
- Lists are mutable (can be changed)
What is a Tuple?
A tuple is an ordered collection of elements enclosed in parentheses ()
Get Saurabh Gandhi’s stories in your inbox
Join Medium for free to get updates from this writer.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
my_tuple = (10, 20, 30)
print(my_tuple)Characteristics of Tuples
Example:
t = (10, "Python", 3.14, True)
print(t)Creating Tuples
# 1. Using parentheses
t = (1,2,3)
# 2. Without parentheses (Tuple Packing)
t = 1, 2, 3
print(t)
#3. Without parentheses (Tuple Packing)
t = (5,)Accessing Tuple Elements (Indexing)
t = (10,20,30,40)
print(t[0]) #10
print(t[-1]) #40Tuple Slicing
t = (10, 20, 30, 40, 50)
print(t[1:4]) # (20, 30, 40)
print(t[:3]) # (10, 20, 30)
print(t[::2]) # (10, 30, 50)Tuple Immutability
You cannot modify elements.
t = (10, 20, 30)
t[0] = 100 # ❌ Error : TypeError: 'tuple' object does not support item assignmentTuple Packing & Unpacking
- Packing
data = ("Raghav", 25, "Developer")- Unpacking
name, age, role = data
print(name)- Using
*Operator (Advanced Unpacking)
t = (1, 2, 3, 4, 5)
a, *b, c = t
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5Tuple Methods
Tuples have only 2 built-in methods:
- count() : Returns the number of times a specified value occurs in a tuple
- index() : Searches the tuple for a specified value and returns the position of where it was found
Example :
t = (1,2,2,3,2)
print(t.count(2)) #3
print(t.index(3)) #3Why Use Tuple Instead of List?
- When data should not change
- Faster performance
- Used as dictionary keys
- Safe data structure
Looping Through Tuple
t = (10, 20, 30)
for item in t:
print(item)Nested Tuples
t = ((1, 2), (3, 4))
print(t[1][0]) # 3Tuple Operations
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # Concatenation
print(t1 * 3) # RepetitionWhen NOT to Use Tuple?
- When data needs frequent modification
- When you need many built-in methods
Questions
- What is a tuple?
- Difference between list and tuple?
- Why are tuples immutable?
- Can a tuple contain mutable objects?
- How to create single element tuple?
- What is tuple packing and unpacking?
- Explain * operator in unpacking.
- Difference between shallow copy in list and tuple?
- Why tuple is faster than list?
- Explain memory optimization in tuples.
- How does immutability help in multithreading?
- What happens if tuple contains a list inside it?
- Explain hashability in context of tuple.
- Internal working difference between list and tuple.










