Fixed Top Ad (Local Preview)800x90 • Slot 6608427872
Tuples and Tuple Methods
✕1. 🔒 Tuples
- Imagine storing fixed information such as date of birth, coordinates, or employee ID details. These values usually should not change accidentally. A tuple is useful for storing this kind of fixed data.
A tuple is a data type in Python used to store multiple items in a single variable.
A tuple is:
✅ Ordered
✅ Immutable
✅ Usually written inside parentheses
( )✅ Able to store different data types 👉 Ordered means items keep their position. 👉 Immutable means we cannot change, add, or remove items after the tuple is created. Example:fruits = ("apple", "banana", "orange")print(fruits)# ➜ ("apple", "banana", "orange") - Tuples are usually created by placing items inside parentheses
( )and separating them with commas. Examples:int_tuple = (1, 2, 3)str_tuple = ("apple", "banana", "orange")mixed_tuple = (1, "hello", 3.14, True)empty_tuple = ()print(int_tuple)print(str_tuple)print(mixed_tuple)print(empty_tuple) - To create a tuple with only one item, we must use a comma.
Example:
data_1 = (1)print(type(data_1))# ➜ <class 'int'>data_2 = (1,)print(type(data_2))# ➜ <class 'tuple'> 📌 Without comma, Python does not treat it as a tuple. - A tuple can store items of any valid Python data type.
Example:
student = ("Ram", 15, 85.5, True)print(student)Output: ("Ram", 15, 85.5, True) Here: "Ram" ➜ String 15 ➜ Integer 85.5 ➜ Float True ➜ Boolean - Imagine a class register where each row has a student's name and age.
Example:
Ram 15
Hari 16
Sita 14
A nested tuple can store this kind of grouped data. A tuple inside another tuple is called a nested tuple.
Example:
student_info = (("Ram", 15), ("Hari", 16), ("Sita", 14))print(student_info)Output: (("Ram", 15), ("Hari", 16), ("Sita", 14)) Nested tuples are useful when we want to store grouped fixed data.
1.1 What is a Tuple?
1.2 Creating Tuples
1.3 Single Item Tuple
1.4 Tuple Items Can Have Different Data Types
1.5 Nested Tuples
2. 🔎 Accessing Tuple Items
- Indexing is used to access a single item from a tuple. Each item in a tuple can be accessed using positive or negative index.
Example:
marks = (10, 20, 30, 40, 50)Index positions: 10 20 30 40 50 0 1 2 3 4 -5 -4 -3 -2 -1print(marks[0])# ➜ 10print(marks[-5])# ➜ 10print(marks[4])# ➜ 50print(marks[-1])# ➜ 50 my_tuple = (10, 20, 30, 40, 50)first_element = my_tuple[0]print(first_element)# ➜ 10print(my_tuple[2])# ➜ 30print(my_tuple[-1])# ➜ 50- Slicing is used to extract a part of a tuple.
Syntax:
tuple_name[start:stop:step]start ➜ Starting index stop ➜ Stopping index, but not included step ➜ Number of items to skip 📌 Start is included. 📌 Stop is not included. 📌 Step is optional. 📌 If start is not given, slicing begins from the start. 📌 If stop is not given, slicing continues till the end. my_tuple = (10, 20, 30, 40, 50)print(my_tuple[1:4])# ➜ (20, 30, 40)print(my_tuple[0:5:2])# ➜ (10, 30, 50)print(my_tuple[:3])# ➜ (10, 20, 30)print(my_tuple[2:])# ➜ (30, 40, 50)print(my_tuple[::-1])# ➜ (50, 40, 30, 20, 10)- Tuples are immutable. This means we cannot change tuple items after the tuple is created.
Example:
my_tuple = (10, 20, 30)my_tuple[1] = 25# ➜ TypeError ⚠️ This line gives an error because tuple items cannot be changed directly. 📌 TypeError means Python cannot perform the operation because the data type does not support it.
2.1 Indexing [ ]
2.2 Indexing Examples
2.3 Slicing [start:stop:step]
2.4 Slicing Examples
2.5 Tuples are Immutable
3. 📦 Tuple Unpacking
- Tuple unpacking means assigning tuple items to multiple variables in a single statement.
Example:
my_tuple = (10, 20)x, y = my_tupleprint(x)# ➜ 10print(y)# ➜ 20 - The number of variables should match the number of tuple items.
Example:
my_tuple = (10, 20, 30)x, y = my_tuple# ➜ ValueError ⚠️ This line gives an error because there are 3 tuple items but only 2 variables. 📌 ValueError means Python could not complete the action because the number of values did not match. - If we do not know how many remaining items there are, we can use
*. Example:a, *b = (1, 2, 3)print(a)# ➜ 1print(b)# ➜ [2, 3] Here:astores the first item.bstores the remaining items as a list. first, second, *remaining = ("Ram", "Hari", "Sita", "Gita")print(first)# ➜ Ramprint(second)# ➜ Hariprint(remaining)# ➜ ["Sita", "Gita"]
3.1 What is Tuple Unpacking?
3.2 Number of Variables Must Match
3.3 Starred Unpacking
3.4 More Unpacking Example
4. 🧰 Tuple Methods and Common Functions
- Because tuples are immutable, they have fewer methods than lists.
Common Tuple Methods:
index()➜ Finds the position of the first occurrence of a valuecount()➜ Counts how many times a value appears index()finds the position of the first occurrence of a value in a tuple. Example:my_tuple = (10, 20, 30, 40, 20, 50)index_of_30 = my_tuple.index(30)print(index_of_30)# ➜ 2print(my_tuple.index(20))# ➜ 1print(my_tuple.index(60))# ➜ ValueError ⚠️ This line gives an error because 60 is not found in the tuple. 📌 ValueError means Python could not complete the action because the value was not found in the tuple.count()counts how many times a value appears in a tuple. Example:my_tuple = (1, 2, 3, 2, 4, 2)print(my_tuple.count(2))# ➜ 3print(my_tuple.count(5))# ➜ 0- Some functions are useful for numeric tuples, while others work with any tuple.
Common Functions:
sum()➜ Adds all numbersmin()➜ Finds smallest valuemax()➜ Finds largest valuelen()➜ Counts number of items Examples:num_tuple = (1, 2, 3, 4, 5)print(sum(num_tuple))# ➜ 15print(min(num_tuple))# ➜ 1print(max(num_tuple))# ➜ 5print(len(num_tuple))# ➜ 5 - Tuples do not support methods that change data.
Invalid methods for tuples:
append()pop()insert()remove()sort()extend()Example:my_tuple = (1, 2, 3)my_tuple.append(4)# ➜ AttributeError ⚠️ This line gives an error because tuples do not haveappend(). 📌 AttributeError means Python does not allow that action on this data type because tuples do not have that tool available. 📌 Use lists when data needs to change. 📌 Use tuples when data should stay fixed.
4.1 Tuple Methods
4.2 index()
4.3 count()
4.4 Common Functions with Tuples
4.5 Invalid List Methods for Tuples
5. 🔗 zip() Function
zip()is used to combine two or more iterables item by item. It creates pairs or groups based on position. Example:names = ("Rabindra", "Bob", "Charlie")ages = (25, 30, 35)combined = zip(names, ages)print(list(combined))# ➜ [("Rabindra", 25), ("Bob", 30), ("Charlie", 35)] Here: "Rabindra" is paired with 25. "Bob" is paired with 30. "Charlie" is paired with 35.numbers_1 = (1, 2, 3)numbers_2 = (4, 5, 6)numbers_3 = (7, 8, 9)zipped_numbers = zip(numbers_1, numbers_2, numbers_3)print(list(zipped_numbers))# ➜ [(1, 4, 7), (2, 5, 8), (3, 6, 9)]- If iterables have different lengths,
zip()stops at the shortest one. Example:numbers_1 = (1, 2, 3)numbers_2 = (4, 5, 6)numbers_3 = (7, 8)zipped_numbers = zip(numbers_1, numbers_2, numbers_3)print(list(zipped_numbers))# ➜ [(1, 4, 7), (2, 5, 8)] 📌 The third item fromnumbers_1andnumbers_2is ignored becausenumbers_3has only two items.
5.1 What is zip()?
5.2 zip() with More Than Two Iterables
5.3 zip() Stops at the Shortest Iterable
