Python Tuples
A tuple in Python is a collection of items separated by commas and enclosed within parentheses ()
.
1. Creating Tuples
You can create tuples containing any data type, similar to lists, but tuples are immutable, meaning their elements cannot be changed after creation.
Example:
numbers = (1, 2, 3, 4, 5)
fruits = ('apple', 'banana', 'orange')
mixed_tuple = (1, 'apple', True, 3.14)
2. Accessing Elements
You can access individual elements of a tuple using indexing, similar to lists.
Example:
numbers = (1, 2, 3, 4, 5)
first_element = numbers[0] # 1
last_element = numbers[-1] # 5
3. Slicing Tuples
You can extract a sublist from a tuple using slicing, similar to lists.
Example:
numbers = (1, 2, 3, 4, 5)
subtuple = numbers[1:4] # (2, 3, 4)
4. Tuple Methods
Since tuples are immutable, they have fewer methods compared to lists. However, they still have useful methods like count()
and index()
.
Example:
numbers = (1, 2, 2, 3, 3, 3)
count_3 = numbers.count(3) # 3
index_2 = numbers.index(2) # 1
Conclusion
Tuples are ordered collections of items in Python, similar to lists but immutable. They are useful for representing fixed collections of items where immutability is desired. Understanding how to create, access, slice, and use tuple methods is essential for working with tuples effectively.