Tuples in Python
What is a Tuple in Python?
A tuple in Python is an immutable collection data type, treated as a predefined class. It stores multiple values, which can be of the same type, different types, or both types. Tuples are commonly used to store related data, such as coordinates or multiple return values from a function, that cannot be changed.
- It is defined using parentheses () and its elements are separated by commas.
- It is an immutable data type, meaning its elements cannot be modified after creation.
- It maintains the insertion order, meaning the elements are stored in the order they were added.
- It is similar to lists, but tuples are immutable, while lists are mutable.
- We can perform both indexing and slicing operations on a tuple object.
- Tuples are immutable, so they don't require shallow copying, but they can be deep copied when containing mutable elements.
Syntax: tuple_obj = tuple(value1, value2, value3, ...)
val = 10 # This is just an integer, not a tuple
print(val, type(val)) # Output: 10 < class 'int' >
value = 100, # This creates a tuple with one element: (100,)
print(value, type(value)) # Output: (100,) < class 'tuple' >
# Represents a student's information: (name, age, GPA, is_enrolled)
student = ("Alice Chen", 20, 3.8, True)
# A tuple to represent the coordinates of a location
location = (40.7128, -74.0060)
latitude = location[0]
longitude = location[1]
print(latitude) # Output: 40.7128
print(longitude) # Output: -74.0060
Pre-defined functions in tuples in Python
Here are the pre-defined functions:
- count(value):
- index(value):
The count() function is used to count the number of occurrences of a specified element. If the specified element is not found, count() returns 0.
Syntax: tuple_obj.count(value)
# Example-1: Using count() to count occurrences of an element in a tuple
fruits = ("apple", "banana", "orange", "apple", "apple")
apple_count = fruits.count("apple")
print(apple_count) # Output: 3
# Example-2: Using count() to determine the frequency of an item in a survey result
survey_responses = ("Yes", "No", "Yes", "Yes", "Maybe", "No", "Yes")
yes_count = survey_responses.count("Yes")
print(yes_count) # Output: 4
The index() function in a list returns the index of the first occurrence of a specified element. If the element is not found, it raises a ValueError.
Syntax: tuple_obj.index(value)
# Find the index of the first occurrence of "Tablet" in the given tuple
products_sold = ("Laptop", "Phone", "Tablet", "Headphones")
product_index = products_sold.index("Tablet")
print(product_index) # Output: 2
# Find the first occurrence of the color "green"
colors = ("red", "blue", "green", "red", "blue", "red")
index_of_green = colors.index("green")
print(index_of_green) # Output: 2
Tuple Unpacking in Python
Tuple unpacking in Python is the process of assigning elements of a tuple to multiple variables in a single statement. It is mostly used for swapping multiple values without an extra variable, unpacking function return values, etc.
- The number of variables on the left must match the elements on the right.
- A mismatch in variables and elements raises a ValueError: too many values to unpack.
# Swapping two numbers without using a temporary variable
num1, num2 = 25, 50
num1, num2 = num2, num1
print(num1) # Output: 50
print(num2) # Output: 25
# Unpacking multiple return values from a function
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
print(x) # Output: 10
print(y) # Output: 20
Exercise
- Top 5 Python Problems on Slicing, Indexing & Nested Lists:
- - Write a Python program to reverse the string "Python" using slicing.
- - Given a list [10, 20, 30, 40, 50], extract [20, 30, 40] using slicing.
- - From [[1, 2, 3], [4, 5, 6], [7, 8, 9]], extract 5 using indexing.
- - Swap the first and last elements of [5, 10, 15, 20].
- - Get [1, 5, 9] from [[1,2,3],[4,5,6],[7,8,9]] using indexing.