In Python, a tuple is a built-in data structure similar to a list, but with some key differences. The main distinction is that tuples are immutable, meaning their elements cannot be modified or reassigned after creation. Here are some key features and operations related to tuples:
# Creating an empty tuple
empty_tuple = ()
# Creating a tuple with elements
coordinates = (3, 4)
fruits = ('apple', 'banana', 'orange')
mixed_tuple = (1, 'hello', 3.14, True)
# Accessing elements by index
first_element = coordinates[0] # 3
second_element = coordinates[1] # 4
# Slicing
subset = fruits[1:3] # ('banana', 'orange')
# Tuples are immutable, so you can't modify elements
# The following line would raise an error:
# coordinates[0] = 5
# Tuple packing
packed_tuple = 1, 'hello', 3.14
# Tuple unpacking
x, y, z = packed_tuple
# Length of a tuple
length = len(coordinates) # 2
# Concatenation
combined_tuple = coordinates + fruits
# Repetition
repeated_tuple = coordinates * 3
# Finding index
index_of_apple = fruits.index('apple')
# Count occurrences
count_of_apple = fruits.count('apple')
Return Multiple Values from a Function: Tuples are often used to return multiple values from a function.
def get_coordinates():
return 3, 4
x, y = get_coordinates()
Immutable Data: Tuples are suitable for situations where the data should not be changed after creation, providing a level of data integrity.
Dictionary Keys: Tuples can be used as keys in dictionaries (unlike lists) because they are hashable.
coordinates_dict = {(3, 4): 'point A', (1, 2): 'point B'}
Named Tuples:
The collections module provides a namedtuple function for creating tuples with named fields, offering a more readable alternative.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=1, y=2)
Tuples are useful for scenarios where you want to ensure the immutability of the data or when you need a lightweight, fixed-size collection of elements.