TUPLES: CREATION, ACCESSING ELEMENTS, AND TUPLE PACKING/UNPACKING.

Tuples are similar to lists in Python, but they are immutable, meaning their elements cannot be changed once they are created. They are created using parentheses () or just by separating the elements with commas.

  1. Creation of Tuples: To create a tuple, you can enclose its elements in parentheses or simply separate them using commas.

Example:

python
# Creating a tuple with parentheses person = ("John", 30, "Male") # Creating a tuple without parentheses coordinates = 10, 20
  1. Accessing Elements: You can access individual elements of a tuple using indexing, just like with lists.

Example:

python
person = ("John", 30, "Male") print(person[0]) # Output: "John" print(person[1]) # Output: 30
  1. Tuple Packing and Unpacking: Tuple packing refers to creating a tuple by combining multiple values together, separated by commas. Tuple unpacking, on the other hand, is the process of assigning the elements of a tuple to separate variables.

Example:

python
# Tuple packing coordinates = 10, 20, 30 print(coordinates) # Output: (10, 20, 30) # Tuple unpacking x, y, z = coordinates print(x) # Output: 10 print(y) # Output: 20 print(z) # Output: 30

Tuple packing is useful when you want to return multiple values from a function, as the function can return a tuple, and the caller can unpack the tuple into separate variables.

python
def get_coordinates(): x = 10 y = 20 z = 30 return x, y, z # Unpacking the returned tuple x, y, z = get_coordinates() print(x) # Output: 10 print(y) # Output: 20 print(z) # Output: 30

Since tuples are immutable, you cannot modify their elements after creation. This immutability makes tuples suitable for use cases where you want to ensure that the data remains unchanged throughout the program's execution.

python
person = ("John", 30, "Male") # This will raise an error, as tuples are immutable person[1] = 35

Tuples are used when you need to group elements together and ensure their integrity throughout the program. They are often used as keys in dictionaries, as dictionary keys must be immutable.