Python Tuples
Tuples are a built-in data structure in Python used to store multiple items in a single variable.
They are immutable, meaning that once a tuple is created, you cannot change its content.
1. Creating Tuples
A tuple is created by placing items inside parentheses (), separated by commas.
Example:
fruits = ("apple", "banana", "cherry")
Single-item tuples require a trailing comma:
single_fruit = ("apple",)
2. Accessing Tuple Items
You can access tuple items using their index. Python uses zero-based indexing.
Example:
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
Negative indexing allows access from the end of the tuple:
print(fruits[-1]) # Output: cherry
3. Updating Tuples
Tuples are immutable, meaning you cannot change, add, or remove items directly. However,
you can create a new tuple based on an existing one.
Example:
fruits = ("apple", "banana", "cherry")
# Create a new tuple by concatenation
new_fruits = fruits + ("orange",)
print(new_fruits) # Output: ('apple', 'banana', 'cherry', 'orange')
4. Unpacking Tuples
You can unpack tuple elements into separate variables.
Example:
fruits = ("apple", "banana", "cherry")
a, b, c = fruits
print(a) # Output: apple
print(b) # Output: banana
print(c) # Output: cherry
You can also use an underscore _ for unwanted variables:
a, _, c = fruits
print(a) # Output: apple
print(c) # Output: cherry
5. Looping Through a Tuple
You can loop through the items in a tuple using a for loop.
Example:
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
6. Joining Tuples
You can join two tuples using the + operator.
Example:
tuple1 = ("a", "b", "c")
tuple2 = ("d", "e", "f")
joined_tuple = tuple1 + tuple2
print(joined_tuple) # Output: ('a', 'b', 'c', 'd', 'e', 'f')
7. Tuple Methods
Python tuples come with a few built-in methods, though fewer than lists, as they are immutable.
Here are some commonly used methods:
● count(): Returns the number of occurrences of a value in a tuple.
numbers = (1, 2, 3, 2)
print(numbers.count(2)) # Output: 2
● index(): Returns the index of the first occurrence of a value.
print(numbers.index(3)) # Output: 2
8. Length of a Tuple
You can find the number of items in a tuple using the len() function.
Example:
print(len(fruits)) # Output: 3
9. Nested Tuples
Tuples can contain other tuples. This is useful for creating complex data structures.
Example:
nested_tuple = (("apple", "banana"), ("cherry", "orange"))
print(nested_tuple[0]) # Output: ('apple', 'banana')
Conclusion
Tuples are a versatile and essential data structure in Python, used for grouping related data
together. Understanding how to create, access, unpack, and manipulate tuples is crucial for
effective programming in Python. Their immutability makes them suitable for fixed collections of
items, providing integrity to the data stored within.