Example 1:What is a Tuple

      
          Defn:A tuple represents a sequence of any objects separated by commas and enclosed in parentheses. A tuple is an immutable object, which means it cannot be changed, and we use it to represent fixed collections of items.

    () — an empty tuple
    (11.0, 29.1, 120) — a tuple containing three numeric objects
    ('John', 'Bear', 'Python', 'Dollars') — a tuple containing four string objects
    ('210', 801, True) — a tuple containing a string, an integer, and a Boolean object
          

Example 2:Create a Tuple and print its type

      
          first_tuple = (8, [11, 12, 13], (14, 15, 16), 197.0)
print(first_tuple)
print(type(first_tuple))          

Example 3:How to Index and Slice a Tuple

      
          print('The first element:', first_tuple[0])
print('The last element:', first_tuple[-1])
print('The data type of the second element:', type(first_tuple[1]))          

Example 4:Further Examples on Slicing

      
          #more slicing
second_tuple = (12, 14, 15, 17, 18, 19)
print(second_tuple[:3])
print(second_tuple[4:])
print(second_tuple[-3:])
print(second_tuple[2:5])          

Example 5:How to concatenate Tuple

      
          tuple_1 = (21, 22)
tuple_2 = (13, 14)
print(tuple_1 + tuple_2)          

Example 6:How to multiply a tuple by an integer

      
          first_tuple = (10, 27, 19, 18)
print(first_tuple * 2)

output:(20,54,38,26)          

Example 7:How to zip tuples

      
          first_names = ('Kimon', 'Zarah', 'John', 'BibiFatima')
last_names = ('Tara', 'Kevin', 'Mohammed', 'Jane')
ages = (19, 25, 29, 23)
zipped = zip(first_names, last_names,ages)
print(zipped)
clients = tuple(zipped)
print(clients)
first_name, last_name, age = clients[2]
print(first_name)
print(last_name)
print(age)
#output:

(('Kimon', 'Tara', 19), ('Zarah', 'Kevin', 25), ('John', 'Mohammed', 29), ('BibiFatima', 'Jane', 23))       
John
Mohammed
29          

Example 8:How to unpack tuple

      
          student_selection_mit = ("Howard","Eden","Jasmine","Agnes")
first_name, second_name,third_name,fourth_name = student_selection_mit
print(first_name)
print(second_name)
print(third_name)
print(fourth_name)          

Example 9:How to unpack Nested tuple

      
          
student_data = ("Christina", 23, ("BSc", "CS", 3.6))
student_name, age, qualification = student_data
print(student_name)
print(age)
print(qualification)
#output:Christina
23
('BSc', 'CS', 3.6)          

Example 10:Unpack with * (asterisk)

      
          student_data = ("Christina", 23, ("BSc", "CS", 3.6),"Secretary")
student_name, age, *other_details = student_data
print(student_name)
print(age)
print(other_details)

#output
Christina
23
[('BSc', 'CS', 3.6), 'Secretary']