Tuples are an immutable and ordered collection of elements in Python. Unlike lists, tuples cannot be changed after creation.
Python Tuples
Tuples are an immutable and ordered collection of elements in Python. Unlike lists, tuples cannot be changed after creation.
Creating a Tuple
# Creating a tuple
numbers = (1, 2, 3, 4, 5)
# Tuple with mixed data types
mixed_tuple = (1, "Hello", 3.14, True)
print(numbers)
print(mixed_tuple)
Accessing Tuple Elements
fruits = ("Apple", "Banana", "Cherry")
print(fruits[0]) # First element
print(fruits[-1]) # Last element
Tuple Immutability
fruits = ("Apple", "Banana", "Cherry")
fruits[1] = "Mango" # This will raise an error since tuples are immutable
Tuple Unpacking
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x, y, z)
Looping Through a Tuple
fruits = ("Apple", "Banana", "Cherry")
for fruit in fruits:
print(fruit)
Checking If an Item Exists
fruits = ("Apple", "Banana", "Cherry")
if "Apple" in fruits:
print("Yes, Apple is in the tuple")
Tuple Concatenation
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4, 5, 6)
Finding Length of a Tuple
numbers = (10, 20, 30, 40)
print(len(numbers)) # Output: 4
Tuple Methods
numbers = (1, 2, 2, 3, 4, 2)
print(numbers.count(2)) # Counts occurrences of 2
print(numbers.index(3)) # Finds index of value 3
Conclusion
Tuples are a useful data structure in Python when you need an ordered and unchangeable sequence of elements.