Tuples and Tuple Methods
✕Introduction to Tuples
- Ordered, Immutable collection of data separated by comma
,enclosed in parenthesis() - Used for storing protected data
int_tuple = (1, 2, 3)str_tuple = ("apple", "banana", "orange")mixed_tuple = (1, "hello", 3.14, True)nested_tuple = (1, (2, 3), ("a", "b"))data_info = 1,empty_tuple = ()complex_tuple = ({"a": 1, "b": [1, 2]}, ("apple", "banana", "orange"))
Examples:
Tuple Unpacking
- Used to assign elements of a tuple to multiple variables in a single statement
my_tuple = (10, 20)x, y = my_tupleprint(x)# 10print(y)# 20a, *b = (1, 2, 3)#a, b = (1, 2, 3)gives errorprint(a)# 1print(b)# [2, 3]
Examples:
Tuple Methods
- Supports all the methods of list that doesn't modify the tuple since tuples are immutable
- Valid Methods: Indexing, Slicing,
index(),count(),len(),min(),max(),sum() - Invalid Methods:
append(),pop(),insert(),remove(),sort(),extend() my_tuple = (1, 2, 3, 2)print(my_tuple[0])# 1my_tuple[1] = 5# Raises TypeErrorprint(my_tuple[1:3])# (2, 3)print(my_tuple.index(2))# 1print(my_tuple.count(2))# 2print(len(my_tuple))# 4print(min((3, 1, 4)))# 1print(max((3, 1, 4)))# 4print(sum((1, 2, 3)))# 6
Examples:
zip function
- Used to combine two or more iterables (like lists, tuples, etc.) element-wise into a single iterable of tuples
names = ["Rabindra", "Bob", "Charlie"]ages = [25, 30, 35]combined = zip(names, ages)print(list(combined))# [("Rabindra", 25), ("Bob", 30), ("Charlie", 35)]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)] (stops at shortest iterable length)
Examples:
