Introduction:
A tuple is an immutable, ordered collection of elements in Python. Once created, the elements within a tuple cannot be modified, added, or removed. Tuples are commonly used to store related data as a single unit and provide a lightweight alternative to lists when immutability is desired.
Creating a Tuple:
Tuples can be created using parentheses ()
or the tuple()
constructor.
Example:
python# Creating a tuple using parentheses
my_tuple = (1, 2, 3, 'hello', True)
# Creating a tuple using tuple() constructor
another_tuple = tuple([4, 5, 6, 'world'])
Accessing Elements:
Elements within a tuple can be accessed using indexing, just like lists. The index starts from 0 for the first element.
Example:
pythonmy_tuple = (10, 20, 30, 40, 50)
# Accessing elements using indexing
print(my_tuple[0]) # Output: 10
print(my_tuple[3]) # Output: 40
Slicing Tuples:
Tuple elements can be retrieved using slicing, which returns a new tuple containing the specified range of elements.
Example:
pythonmy_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
# Slicing tuple to get elements from index 2 to 5 (exclusive)
sliced_tuple = my_tuple[2:5]
print(sliced_tuple) # Output: (3, 4, 5)
Tuple Packing and Unpacking:
Tuple packing involves combining multiple values into a single tuple, while tuple unpacking splits a tuple into multiple variables.
Example:
python# Tuple packing
person = ('John', 30, 'New York')
# Tuple unpacking
name, age, city = person
print(name) # Output: 'John'
print(age) # Output: 30
print(city) # Output: 'New York'
Use Cases:
- Tuples are useful when the order of elements matters, but the data should not change.
- They can be used as keys in dictionaries due to their immutability.
Conclusion:
Tuples in Python are versatile data structures that provide immutability and order to collections of elements. They are widely used in various scenarios where data integrity and consistency are essential.
0 Comments