Tuples and Tuple Methods

Introduction to Tuples

  • Ordered, Immutable collection of data separated by comma , enclosed in parenthesis ()
  • Used for storing protected data
  • Examples:
    1. 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"))

Tuple Unpacking

  • Used to assign elements of a tuple to multiple variables in a single statement
  • Examples:
    1. my_tuple = (10, 20) x, y = my_tuple print(x) # 10 print(y) # 20 a, *b = (1, 2, 3) # a, b = (1, 2, 3) gives error print(a) # 1 print(b) # [2, 3]

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()
  • Examples:
    1. my_tuple = (1, 2, 3, 2) print(my_tuple[0]) # 1 my_tuple[1] = 5 # Raises TypeError print(my_tuple[1:3]) # (2, 3) print(my_tuple.index(2)) # 1 print(my_tuple.count(2)) # 2 print(len(my_tuple)) # 4 print(min((3, 1, 4))) # 1 print(max((3, 1, 4))) # 4 print(sum((1, 2, 3))) # 6

zip function

  • Used to combine two or more iterables (like lists, tuples, etc.) element-wise into a single iterable of tuples
  • Examples:
    1. 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)