Python Tuples
Python Tuples
A tuple is a built-in Python data structure used to store multiple values in a single variable.
colors = ("red", "green", "blue")
Tuples look and behave much like lists, with one key difference: a tuple cannot be changed after it is created. This makes tuples ideal for data that should stay fixed, such as coordinates, RGB color values, dates, or the days of the week.
Tuples Among Python's Collection Types
Python provides four main built-in collection data types:
| Collection | Ordered | Changeable | Duplicates | Syntax |
|---|---|---|---|---|
| List | Yes | Yes | Allowed | [ ] |
| Tuple | Yes | No | Allowed | ( ) |
| Set | No | Can add/remove items | Not allowed | { } |
| Dictionary | Yes | Yes | No duplicate keys | {key: value} |
Each collection type has its own behavior and use cases.
What Is a Tuple?
A tuple is:
- Ordered — items keep their position.
- Immutable — items cannot be changed, added, or removed after creation.
- Allows duplicates — the same value can appear more than once.
Tuples are written with round brackets ( ).
Creating a Tuple
fruits = ("mango", "orange", "grapes")
print(fruits)
Expected output:
('mango', 'orange', 'grapes')
Strictly speaking, it is the comma that creates a tuple; the parentheses mainly improve readability. This also creates a tuple:
point = 4, 7
print(point)
print(type(point))
Expected output:
(4, 7)
<class 'tuple'>
Why Use a Tuple Instead of a List?
- Safety: Data that must not change is protected from accidental modification.
- Clear intent: A tuple tells other developers that the collection has a fixed structure.
- Dictionary keys: Tuples (containing only immutable values) can be used as dictionary keys or set items; lists cannot.
- Returning multiple values: Functions commonly return several values as a tuple.
locations = {(13.08, 80.27): "Chennai", (19.07, 72.87): "Mumbai"}
print(locations[(13.08, 80.27)])
Expected output:
Chennai
Tuple Characteristics
Ordered
Items in a tuple have a fixed order, so each item can be accessed by its index.
numbers = (10, 20, 30)
print(numbers[0])
Expected output:
10
Immutable
Once a tuple is created, its items cannot be modified.
languages = ("Python", "Java", "C++")
languages[1] = "Go"
Output:
TypeError: 'tuple' object does not support item assignment
Tuples also have no append(), remove(), or sort() methods.
Note: Immutability applies to the tuple's references, not necessarily to the objects inside it. If a tuple contains a list, that list can still be changed:
data = ([1, 2], 3)followed bydata[0].append(9)works. The tuple still holds the same list object — the list itself changed.
Allows Duplicate Values
cities = ("Paris", "London", "Paris", "Tokyo")
print(cities)
Expected output:
('Paris', 'London', 'Paris', 'Tokyo')
Tuple Length
Use len() to find how many items a tuple contains.
subjects = ("Math", "Science", "History")
print(len(subjects))
Expected output:
3
Creating a Tuple With One Item
A single-item tuple must include a trailing comma. Without it, the parentheses are treated as ordinary grouping parentheses, and you get the value itself.
single_item = ("Python",)
print(type(single_item))
not_a_tuple = ("Python")
print(type(not_a_tuple))
Expected output:
<class 'tuple'>
<class 'str'>
("Python") is just the string "Python" in parentheses — in the same way that (5) is just the integer 5. The comma is what makes it a tuple.
An empty tuple is written as ().
Tuple Items and Data Types
Tuple items can be of any data type.
names = ("Alice", "Bob", "Charlie")
scores = (85, 90, 78)
status = (True, False, True)
A tuple can also contain mixed data types:
profile = ("John", 28, True, 5.9)
print(profile)
Expected output:
('John', 28, True, 5.9)
Checking the Tuple Data Type
data = ("pen", "pencil", "eraser")
print(type(data))
Expected output:
<class 'tuple'>
Using the tuple() Constructor
The tuple() constructor converts any iterable into a tuple.
vehicles = tuple(["car", "bike", "bus"])
print(vehicles)
Expected output:
('car', 'bike', 'bus')
Note: The square brackets inside the parentheses create a list, which
tuple()then converts into a tuple.
Accessing Tuple Items
Tuple items are accessed by index, exactly like list items, using square brackets.
Access by Index
Indexing starts at 0, so the first item is at position 0.
animals = ("dog", "cat", "rabbit")
print(animals[1])
Expected output:
cat
Negative Indexing
Negative indexes count from the end:
-1→ the last item-2→ the second-to-last item
planets = ("Mercury", "Venus", "Earth", "Mars")
print(planets[-1])
Expected output:
Mars
Accessing a Range of Items
Slicing returns a new tuple containing the selected items.
Note: The start index is included; the end index is excluded.
colors = ("red", "blue", "green", "yellow", "purple", "orange")
print(colors[2:5])
Expected output:
('green', 'yellow', 'purple')
The slice returns the items at indexes 2, 3, and 4.
Slicing From the Beginning
months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun")
print(months[:3])
Expected output:
('Jan', 'Feb', 'Mar')
Slicing to the End
countries = ("India", "USA", "UK", "Canada", "Australia")
print(countries[2:])
Expected output:
('UK', 'Canada', 'Australia')
Slicing With Negative Indexes
numbers = (10, 20, 30, 40, 50, 60, 70)
print(numbers[-5:-2])
Expected output:
(30, 40, 50)
The slice starts at the fifth item from the end (30) and stops before the second item from the end (60).
Checking Whether an Item Exists
languages = ("Python", "Java", "C", "Go")
if "Python" in languages:
print("Python is available in the tuple.")
Expected output:
Python is available in the tuple.
Updating Tuples
Tuples are immutable, so you cannot directly modify, add, or remove their items. However, there are safe workarounds. Each workaround creates a new tuple and assigns it to the variable; the original tuple object is never changed.
Changing a Value: Convert to a List and Back
- Convert the tuple into a list.
- Make the change.
- Convert the list back into a tuple.
colors = ("red", "green", "blue")
temp_list = list(colors)
temp_list[0] = "yellow"
colors = tuple(temp_list)
print(colors)
Expected output:
('yellow', 'green', 'blue')
Adding Items
Method 1: Convert to a List
This is the most flexible approach when adding one or more items.
cities = ("Delhi", "Mumbai", "Chennai")
city_list = list(cities)
city_list.append("Kolkata")
cities = tuple(city_list)
print(cities)
Expected output:
('Delhi', 'Mumbai', 'Chennai', 'Kolkata')
Method 2: Join Two Tuples
Create a new tuple containing the new items and concatenate it with the existing one.
Note: Remember the trailing comma when creating a single-item tuple.
tools = ("Python", "Git", "Docker")
new_tool = ("Kubernetes",)
tools = tools + new_tool
print(tools)
Expected output:
('Python', 'Git', 'Docker', 'Kubernetes')
Without the comma, ("Kubernetes") would be a string, and tools + "Kubernetes" would raise TypeError: can only concatenate tuple (not "str") to tuple.
Removing Items
Direct removal is not allowed. Convert the tuple to a list, remove the item, and convert it back.
subjects = ("Math", "Science", "History")
subject_list = list(subjects)
subject_list.remove("Science")
subjects = tuple(subject_list)
print(subjects)
Expected output:
('Math', 'History')
Tip: If you find yourself frequently converting a tuple to a list to change it, a list is probably the better data type for that data.
Deleting a Tuple Entirely
You cannot delete individual items, but you can delete the entire tuple with del.
languages = ("Python", "Java", "C++")
del languages
print(languages)
Output:
NameError: name 'languages' is not defined
Packing and Unpacking Tuples
Packing
Packing means grouping several values into a tuple.
languages = ("Python", "JavaScript", "Go")
Unpacking
Unpacking means extracting the values of a tuple into separate variables in a single statement.
Note: The number of variables must match the number of items in the tuple.
languages = ("Python", "JavaScript", "Go")
lang1, lang2, lang3 = languages
print(lang1)
print(lang2)
print(lang3)
Expected output:
Python
JavaScript
Go
If the counts do not match, Python raises a ValueError such as too many values to unpack (expected 2).
Using the Asterisk (*) to Collect Remaining Values
When there are more values than variables, prefix one variable with *. That variable collects the remaining values into a list.
Asterisk at the End
colors = ("red", "green", "blue", "yellow", "purple")
primary, secondary, *others = colors
print(primary)
print(secondary)
print(others)
Expected output:
red
green
['blue', 'yellow', 'purple']
Asterisk in the Middle
The starred variable can also be in the middle. Python first fills the variables before and after it, and the starred variable receives everything in between.
devices = ("Laptop", "Tablet", "Phone", "Smartwatch", "TV")
first, *portable, last = devices
print(first)
print(portable)
print(last)
Expected output:
Laptop
['Tablet', 'Phone', 'Smartwatch']
TV
Only one starred variable is allowed in an unpacking assignment.
Practical Example: Returning Multiple Values From a Function
When a function returns several comma-separated values, Python packs them into a tuple. The caller can unpack them directly.
def min_max(numbers):
return min(numbers), max(numbers)
lowest, highest = min_max([42, 7, 19, 88])
print("Lowest:", lowest)
print("Highest:", highest)
Expected output:
Lowest: 7
Highest: 88
Looping Through Tuples
Tuples are iterable, so you can loop through them in the same ways as lists.
Looping Over Values With for
frameworks = ("Django", "Flask", "FastAPI")
for framework in frameworks:
print(framework)
Expected output:
Django
Flask
FastAPI
Looping With Index Positions
scores = (85, 90, 78, 92)
for index in range(len(scores)):
print("Index:", index, "Value:", scores[index])
Expected output:
Index: 0 Value: 85
Index: 1 Value: 90
Index: 2 Value: 78
Index: 3 Value: 92
enumerate(scores) is a cleaner alternative that provides the index and value together.
Looping With while
countries = ("India", "Japan", "Germany")
i = 0
while i < len(countries):
print(countries[i])
i += 1
Expected output:
India
Japan
Germany
Choosing the Right Loop
| Loop Type | Best Use Case |
|---|---|
for loop | Simple iteration over values |
for with range(len()) or enumerate() | When the index is required |
while loop | When you need manual control over iteration |
Joining and Repeating Tuples
Because tuples are immutable, these operations always create new tuples.
Combining Tuples With +
letters = ("x", "y", "z")
numbers = (10, 20, 30)
combined = letters + numbers
print(combined)
Expected output:
('x', 'y', 'z', 10, 20, 30)
Joining More Than Two Tuples
weekdays = ("Mon", "Tue")
weekend = ("Sat", "Sun")
extras = ("Holiday",)
schedule = weekdays + weekend + extras
print(schedule)
Expected output:
('Mon', 'Tue', 'Sat', 'Sun', 'Holiday')
Repeating Tuples With *
The * operator repeats a tuple's items a specified number of times.
patterns = ("A", "B")
result = patterns * 3
print(result)
Expected output:
('A', 'B', 'A', 'B', 'A', 'B')
Practical Example: Generating Repeated Data
levels = ("Beginner", "Intermediate")
courses = levels * 2
print(courses)
Expected output:
('Beginner', 'Intermediate', 'Beginner', 'Intermediate')
Tuple Methods
Because tuples cannot be modified, they have only two methods:
| Method | Purpose |
|---|---|
count() | Returns how many times a value appears |
index() | Returns the index of the first matching value |
count()
ratings = (5, 4, 5, 3, 5, 4)
total_fives = ratings.count(5)
print(total_fives)
Expected output:
3
index()
cities = ("Paris", "London", "Tokyo", "London")
position = cities.index("London")
print(position)
Expected output:
1
Only the first match is reported, even though "London" appears twice.
Note: If the value does not exist,
index()raises aValueError.
Handling Missing Values Safely
Check whether the value exists before calling index():
items = ("pen", "pencil", "eraser")
if "eraser" in items:
print(items.index("eraser"))
else:
print("Item not found")
Expected output:
2
Common Mistakes
| Mistake | Example | Problem |
|---|---|---|
| Forgetting the comma in a single-item tuple | ("Python") | Creates a string, not a tuple |
| Trying to change an item | t[0] = 5 | TypeError |
| Calling list methods on a tuple | t.append(5) | AttributeError |
| Unpacking with the wrong number of variables | a, b = (1, 2, 3) | ValueError |
Related Concepts
- Python Lists — the mutable alternative to tuples
- Python Sets — unordered collections of unique items
- Python Dictionaries — where tuples can be used as keys
- Python Functions — returning multiple values as a tuple