Tuples
Learn how to store ordered and immutable collections of values using Python Tuples.
What is a Tuple?
A Tuple is an ordered collection of values in Python. Tuples are similar to Lists, but the important difference is that Tuples are immutable.
Immutable means that once a Tuple is created, its elements cannot be changed.
Tuples are useful when we want to keep a group of values unchanged.
- Ordered
- Immutable
- Allow duplicate values
- Support different data types
- Support indexing and slicing
Creating a Tuple
Tuples are normally created using
parentheses ().
courses = ("Python", "Java", ".NET")
print(courses)
Output:
('Python', 'Java', '.NET')
Tuple Packing
Python also allows us to create a Tuple without explicitly writing parentheses.
student = "Rahul", 22, "Python"
print(student)
Output:
('Rahul', 22, 'Python')
This is called Tuple Packing.
Single Element Tuple
A single-element Tuple must contain a comma.
course = ("Python",)
print(course)
print(type(course))
Output:
('Python',)
<class 'tuple'>
Without Comma
course = ("Python")
print(type(course))
Output:
<class 'str'>
The comma is what makes it a Tuple.
Tuple with Different Data Types
student = (
"Rahul",
22,
85.5,
True
)
print(student)
Output:
('Rahul', 22, 85.5, True)
Tuple Indexing
Tuple indexing starts from 0.
courses = ("Python", "Java", ".NET", "MERN")
print(courses[0])
print(courses[1])
print(courses[2])
print(courses[3])
Output:
Python
Java
.NET
MERN
Negative Indexing
Negative indexes allow us to access elements from the end of the Tuple.
courses = ("Python", "Java", ".NET", "MERN")
print(courses[-1])
print(courses[-2])
Output:
MERN
.NET
Tuple Slicing
Slicing extracts a portion of a Tuple.
courses = (
"Python",
"Java",
".NET",
"MERN",
"Data Science"
)
print(courses[1:4])
Output:
('Java', '.NET', 'MERN')
The ending index is not included.
Tuples are Immutable
Once a Tuple is created, its individual elements cannot be changed.
student = ("Rahul", 22, "Python")
student[1] = 23
The above code produces a TypeError.
This is the major difference between a List and a Tuple.
Finding Tuple Length
The len() function returns the
number of elements.
courses = ("Python", "Java", ".NET", "MERN")
print(len(courses))
Output:
4
Searching in a Tuple
The in operator checks whether
an item exists in the Tuple.
courses = ("Python", "Java", ".NET")
print("Python" in courses)
print("PHP" in courses)
Output:
True
False
count()
The count() method returns the
number of times a value appears.
courses = (
"Python",
"Java",
"Python",
".NET",
"Python"
)
print(courses.count("Python"))
Output:
3
index()
The index() method returns the
position of the first matching element.
courses = ("Python", "Java", ".NET")
print(courses.index("Java"))
Output:
1
Looping Through a Tuple
A for loop can be used to process
every element of a Tuple.
courses = ("Python", "Java", ".NET", "MERN")
for course in courses:
print(course)
Output:
Python
Java
.NET
MERN
Tuple Unpacking
Tuple unpacking allows us to assign Tuple elements to separate variables.
student = ("Rahul", 22, "Python")
name, age, course = student
print(name)
print(age)
print(course)
Output:
Rahul
22
Python
Extended Tuple Unpacking
The * operator can collect
multiple remaining values.
courses = (
"Python",
"Java",
".NET",
"MERN"
)
first, *remaining = courses
print(first)
print(remaining)
Output:
Python
['Java', '.NET', 'MERN']
Joining Tuples
Two Tuples can be combined using the
+ operator.
basic_courses = ("Python", "Java")
advanced_courses = (".NET", "MERN")
all_courses = basic_courses + advanced_courses
print(all_courses)
Output:
('Python', 'Java', '.NET', 'MERN')
Repeating a Tuple
The * operator can repeat the
elements of a Tuple.
numbers = (1, 2)
result = numbers * 3
print(result)
Output:
(1, 2, 1, 2, 1, 2)
Converting List to Tuple
The tuple() function can convert
another iterable into a Tuple.
courses = ["Python", "Java", ".NET"]
course_tuple = tuple(courses)
print(course_tuple)
Output:
('Python', 'Java', '.NET')
Converting Tuple to List
A Tuple can be converted to a List using
list().
courses = ("Python", "Java", ".NET")
course_list = list(courses)
course_list.append("MERN")
print(course_list)
Output:
['Python', 'Java', '.NET', 'MERN']
CIIT Example 📩👀
Suppose CIIT wants to store fixed information about a training batch.
batch = (
"Python Full Stack",
"Morning",
"6 Months",
"Pune"
)
print("Course:", batch[0])
print("Timing:", batch[1])
print("Duration:", batch[2])
print("Location:", batch[3])
Output:
Course: Python Full Stack
Timing: Morning
Duration: 6 Months
Location: Pune
Since these batch details may be treated as fixed information, a Tuple is a suitable choice.
List vs Tuple
| Feature | List | Tuple |
|---|---|---|
| Syntax | [] |
() |
| Ordered | Yes | Yes |
| Mutable | Yes | No |
| Duplicates | Allowed | Allowed |
| Indexing | Supported | Supported |
| Slicing | Supported | Supported |
| Typical use | Changing collections | Fixed collections |
Common Mistakes
- Forgetting the comma when creating a single-element Tuple.
- Trying to update a Tuple element.
- Assuming Tuple methods are the same as all List methods.
- Using a Tuple when the data needs frequent modifications.
-
Forgetting that Tuple indexes start from
0.
Interview Points
- What is a Tuple in Python?
- What is the difference between List and Tuple?
- Why are Tuples immutable?
- How do you create a single-element Tuple?
- Can a Tuple contain different data types?
- What is Tuple unpacking?
- How can you convert a Tuple into a List?
CIIT Learning Point
Tuples are useful when data should remain unchanged. Understanding indexing, slicing, unpacking, Tuple methods and the difference between mutable Lists and immutable Tuples is important for writing reliable Python programs.
CIIT Practice Tasks
- Create a Tuple containing five course names and print each course.
- Access the first and last elements using positive and negative indexing.
- Create a Tuple of student details and unpack it into separate variables.
- Count how many times "Python" appears in a Tuple.
- Convert a List into a Tuple.
- Convert a Tuple into a List and add a new element.
- Create a Tuple containing fixed CIIT batch information and display each value.
Summary :
Python Tuples are ordered and immutable collections used to store values that should remain unchanged. Tuples support indexing, negative indexing, slicing, searching, counting, unpacking and iteration. Important methods include count() and index(). Tuples can also be converted to Lists when modification is required.