Tuples and Tuple Methods

1. 🔒 Tuples

    1.1 What is a Tuple?
    1. 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")
    1.2 Creating Tuples
    1. 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)
    1.3 Single Item Tuple
    1. 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.
    1.4 Tuple Items Can Have Different Data Types
    1. 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
    1.5 Nested Tuples
    1. 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.

2. 🔎 Accessing Tuple Items

    2.1 Indexing [ ]
    1. 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 -1 print(marks[0]) # ➜ 10 print(marks[-5]) # ➜ 10 print(marks[4]) # ➜ 50 print(marks[-1]) # ➜ 50
    2.2 Indexing Examples
    1. my_tuple = (10, 20, 30, 40, 50)first_element = my_tuple[0] print(first_element) # ➜ 10 print(my_tuple[2]) # ➜ 30 print(my_tuple[-1]) # ➜ 50
    2.3 Slicing [start:stop:step]
    1. 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.
    2.4 Slicing Examples
    1. 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)
    2.5 Tuples are Immutable
    1. 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.

3. 📦 Tuple Unpacking

    3.1 What is Tuple Unpacking?
    1. Tuple unpacking means assigning tuple items to multiple variables in a single statement. Example: my_tuple = (10, 20)x, y = my_tuple print(x) # ➜ 10 print(y) # ➜ 20
    3.2 Number of Variables Must Match
    1. 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.
    3.3 Starred Unpacking
    1. If we do not know how many remaining items there are, we can use *. Example: a, *b = (1, 2, 3)print(a) # ➜ 1 print(b) # ➜ [2, 3] Here: a stores the first item. b stores the remaining items as a list.
    3.4 More Unpacking Example
    1. first, second, *remaining = ("Ram", "Hari", "Sita", "Gita")print(first) # ➜ Ram print(second) # ➜ Hari print(remaining) # ➜ ["Sita", "Gita"]

4. 🧰 Tuple Methods and Common Functions

    4.1 Tuple Methods
    1. Because tuples are immutable, they have fewer methods than lists. Common Tuple Methods: index() ➜ Finds the position of the first occurrence of a value count() ➜ Counts how many times a value appears
    4.2 index()
    1. 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) # ➜ 2 print(my_tuple.index(20)) # ➜ 1 print(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.
    4.3 count()
    1. 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)) # ➜ 3 print(my_tuple.count(5)) # ➜ 0
    4.4 Common Functions with Tuples
    1. Some functions are useful for numeric tuples, while others work with any tuple. Common Functions: sum() ➜ Adds all numbers min() ➜ Finds smallest value max() ➜ Finds largest value len() ➜ Counts number of items Examples: num_tuple = (1, 2, 3, 4, 5)print(sum(num_tuple)) # ➜ 15 print(min(num_tuple)) # ➜ 1 print(max(num_tuple)) # ➜ 5 print(len(num_tuple)) # ➜ 5
    4.5 Invalid List Methods for Tuples
    1. 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 have append(). 📌 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.

5. 🔗 zip() Function

    5.1 What is zip()?
    1. 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.
    5.2 zip() with More Than Two Iterables
    1. 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)]
    5.3 zip() Stops at the Shortest Iterable
    1. 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 from numbers_1 and numbers_2 is ignored because numbers_3 has only two items.

Practice QuestionsNot started

  1. 1. Creating and Accessing Tuples

    Question 1 of 5

      1.1 Practice creating and accessing tuples:
      1. Create a tuple named employee_names with names of three employees.
      2. Create a tuple named employee_salaries with salaries of three employees.
      3. Display the first employee name.
      4. Display the last employee name using negative indexing.
      5. Display the first two salaries using slicing.
      6. Create a tuple with only one item and display its type.
      7. Create a nested tuple in this format: (("Ram", 15), ("Hari", 16), ("Sita", 14)). Display the second student's age.
  2. 2. Tuple Operations

    Question 2 of 5

      2.1 Create salary_tuple = (20000, 25000, 30000)
      1. Find and display the total number of employees.
      2. Find and display total salary.
      3. Find and display average salary.
      4. Find and display highest salary.
      5. Find and display lowest salary.
      6. Count and display how many employees have salary 25000.
      7. Find and display the index of salary 30000.
      8. Try to update salary at index 1 to 35000 and observe the error.
  3. 3. Tuple Unpacking

    Question 3 of 5

      3.1 Create employee = ("Rabindra", 25000)
      1. Unpack employee into name and salary variables.
      2. Display name.
      3. Display salary.
      3.2 Create numbers = (1, 2, 3, 4, 5)
      1. Use starred unpacking to store first value in a and remaining values in b.
      2. Display a.
      3. Display b.
  4. 4. Employee Salary Challenge

    Question 4 of 5

      4.1 Create employee_names = ("Rabindra", "Bob", "Charlie") and employee_salaries = (20000, 25000, 30000)
      1. Display total number of employees.
      2. Display total salary.
      3. Display average salary.
      4. Display highest salary.
      5. Display lowest salary.
      6. Display the name of employee with highest salary.
      7. Display the name of employee with lowest salary.
      8. Display number of employees with salary 25000.
      9. Zip employee_names and employee_salaries into a single list of tuples and display it.
  5. 5. zip() Practice

    Question 5 of 5

      5.1 Create names = ("Ram", "Hari", "Sita") and marks = (80, 75, 90)
      1. Use zip() to combine names and marks.
      2. Convert the result into a list.
      3. Display the combined list.
      4. Create another tuple subjects = ("Math", "Science").
      5. Zip names, marks, and subjects together.
      6. Display the result and observe how zip() stops at the shortest tuple.