In this Python tutorial, you will learn how to create a tuple, access tuple elements using positive and negative indexes, extract values with slicing, and iterate over a tuple with practical examples.
What Is a Tuple in Python?
A Python tuple is an ordered collection of values. Like a list, a tuple can contain values of different data types, and each value can be accessed by its index.
The main difference between a tuple and a list is that a tuple is immutable. After a tuple is created, you cannot replace, add, or remove its individual elements.
- Ordered: Each value has a fixed position.
- Indexed: Indexes start at
0. - Immutable: Individual tuple elements cannot be reassigned.
- Allows duplicates: The same value may occur more than once.
- Supports mixed data types: A tuple may contain numbers, strings, Boolean values, or other objects.
How to Define a Python Tuple
A tuple is commonly written as comma-separated values enclosed in parentheses ().
For example, (14, "Raghu") is a tuple containing an integer and a string.
tuple1 = (14, 'Raghu')
You can access the first element using tuple1[0] and the second element using tuple1[1].
Create an Empty Tuple in Python
Use an empty pair of parentheses to create a tuple with no elements.
empty_tuple = ()
print(empty_tuple)
print(type(empty_tuple))
Output
()
<class 'tuple'>
Create a Single-Element Python Tuple
A single-element tuple requires a trailing comma. Parentheses alone do not make a value a tuple.
single_item_tuple = (25,)
not_a_tuple = (25)
print(type(single_item_tuple))
print(type(not_a_tuple))
Output
<class 'tuple'>
<class 'int'>
The comma creates the tuple. Parentheses are mainly used to make the tuple expression clear.
Access Python Tuple Items by Index
Tuple indexes start at 0. Therefore, the first item is at index 0, the second item is at index 1, and so on.
In the following example, we define a tuple containing an integer and a string, and then access both elements by index.
example.py
myTuple = (14, 'Raghu')
print(myTuple[0])
print(myTuple[1])
Output
14
Raghu
Access Tuple Elements with Negative Indexes
Python also supports negative indexing. Index -1 refers to the last element, -2 refers to the second-last element, and so on.
languages = ('Python', 'Java', 'Go', 'Swift')
print(languages[-1])
print(languages[-2])
Output
Swift
Go
Tuple Index Out of Range Error
Accessing an index that does not exist raises an IndexError.
numbers = (10, 20, 30)
print(numbers[3])
The valid indexes are 0, 1, and 2. Index 3 is outside the tuple.
IndexError: tuple index out of range
Slice a Python Tuple
Tuple slicing returns a new tuple containing a selected range of elements. Use the syntax tuple[start:stop:step].
The start index is included, while the stop index is excluded.
numbers = (10, 20, 30, 40, 50, 60)
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
print(numbers[::2])
Output
(20, 30, 40)
(10, 20, 30)
(40, 50, 60)
(10, 30, 50)
Python Tuples Are Immutable
Tuple elements cannot be reassigned after the tuple is created. In the following example, Python raises a TypeError when the program tries to replace an element.
example.py
myTuple = (14, 'Raghu')
myTuple[0] = 25
myTuple[1] = 'Tim'
Output
Traceback (most recent call last):
File "example1.py", line 3, in <module>
myTuple[0] = 25
TypeError: 'tuple' object does not support item assignment
Python tuples do not support item assignment. To use different values, create a new tuple.
old_tuple = (14, 'Raghu')
new_tuple = (25, 'Tim')
print(old_tuple)
print(new_tuple)
Mutable Objects Inside a Tuple
A tuple cannot point to a different element after creation. However, if one of its elements is a mutable object such as a list, the contents of that object can still change.
record = ('Raghu', [70, 80])
record[1].append(90)
print(record)
Output
('Raghu', [70, 80, 90])
The tuple still contains the same list object, but that list’s contents have been modified.
Iterate Over a Python Tuple
A for loop is the simplest way to iterate over all elements of a tuple.
example.py
myTuple = (14, 'Raghu')
for element in myTuple:
print(element)
Output
14
Raghu
Iterate Over a Tuple with Indexes
Use enumerate() when you need both the index and value during iteration.
colors = ('red', 'green', 'blue')
for index, color in enumerate(colors):
print(index, color)
Output
0 red
1 green
2 blue
Unpack Values from a Python Tuple
Tuple unpacking assigns tuple elements to multiple variables in a single statement. The number of variables must normally match the number of tuple elements.
person = ('Raghu', 28, 'Hyderabad')
name, age, city = person
print(name)
print(age)
print(city)
Output
Raghu
28
Hyderabad
Use an Asterisk While Unpacking a Tuple
An asterisk can collect multiple remaining values into a list.
numbers = (10, 20, 30, 40, 50)
first, *middle, last = numbers
print(first)
print(middle)
print(last)
Output
10
[20, 30, 40]
50
Useful Python Tuple Operations
Python provides operators and built-in functions for inspecting and combining tuples.
Find the Number of Tuple Elements
values = (10, 20, 30, 40)
print(len(values))
Output
4
Check Whether a Value Exists in a Tuple
languages = ('Python', 'Java', 'Go')
print('Java' in languages)
print('Swift' in languages)
Output
True
False
Combine and Repeat Python Tuples
The + operator combines tuples, while the * operator repeats their elements. Both operations create new tuples.
first = (1, 2)
second = (3, 4)
combined = first + second
repeated = first * 3
print(combined)
print(repeated)
Output
(1, 2, 3, 4)
(1, 2, 1, 2, 1, 2)
Python Tuple Methods: count() and index()
Because tuples are immutable, they provide only two methods for examining their contents.
Count Matching Values in a Tuple
The count() method returns the number of times a value appears.
numbers = (10, 20, 10, 30, 10)
print(numbers.count(10))
Output
3
Find the Index of a Tuple Value
The index() method returns the index of the first matching value. It raises a ValueError if the value is absent.
languages = ('Python', 'Java', 'Go', 'Java')
print(languages.index('Java'))
Output
1
Convert Between Python Tuples and Lists
Use list() to convert a tuple to a list and tuple() to convert a list or another iterable to a tuple.
coordinates = (10, 20)
coordinate_list = list(coordinates)
coordinate_list.append(30)
updated_coordinates = tuple(coordinate_list)
print(coordinate_list)
print(updated_coordinates)
Output
[10, 20, 30]
(10, 20, 30)
Python Tuple Compared with a List
| Feature | Tuple | List |
|---|---|---|
| Common syntax | (1, 2, 3) | [1, 2, 3] |
| Can individual elements be replaced? | No | Yes |
| Can elements be added or removed? | No | Yes |
| Supports indexing and slicing? | Yes | Yes |
| Typical use | Fixed records or values that should not change | Collections that need modification |
Choose a tuple when the collection represents a fixed set of values. Choose a list when the collection must grow, shrink, or have elements replaced.
Common Python Tuple Questions
Are parentheses required to create a tuple?
No. The comma creates a tuple, so values = 1, 2, 3 is valid. Parentheses are commonly used because they make the tuple easier to recognize and are required in some expressions.
Why does a single-item tuple need a comma?
Without a comma, Python treats parentheses as normal grouping. Therefore, (10) is an integer, while (10,) is a tuple.
Can a Python tuple contain duplicate values?
Yes. A tuple may contain the same value multiple times. Use the count() method to determine how many times a value occurs.
Can a Python tuple contain a list?
Yes. A tuple can contain a list or another mutable object. The tuple cannot be reassigned to a different list, but the existing list’s contents may still be modified.
Summary of Python Tuple Operations
A Python tuple is an ordered, indexed, and immutable collection. Create tuples with comma-separated values, access their elements with positive or negative indexes, use slicing to extract ranges, and iterate with a for loop or enumerate(). Tuples also support unpacking, membership tests, concatenation, repetition, and the count() and index() methods.
In this Python Tutorial, we learned how to define a Python tuple, access and slice its elements, understand tuple immutability, unpack values, and iterate over a tuple.
TutorialKart.com