In Python, a Tuple is a built-in data structure used to store a collection of items in a single variable. While they appear very similar to lists, they have a fundamental difference: Tuples are immutable, meaning once they are created, their contents cannot be changed.
Ordered: Tuples keep the items in a specific sequence. You access them using indices starting from 0.
Immutable: This is the defining feature. You cannot add, remove, or modify elements after the tuple is defined. This makes them faster and safer for data that shouldn't change (like geographic coordinates).
Allow Duplicates: Since items are indexed, multiple items can have the same value.
Heterogeneous: Like lists, tuples can store a mix of different data types (integers, strings, etc.) in one collection.
Speed: Tuples are slightly faster than lists because their fixed size allows Python to optimize memory allocation.
Data Integrity: Use tuples for data that should be "read-only." This prevents accidental changes to constants in your program.
Dictionary Keys: Because tuples are immutable, they can be used as keys in dictionaries, whereas lists cannot.
Tuples are created by placing elements inside parentheses () and separating them with commas.
# Creating tuples empty_tuple = () fruits = ("apple", "banana", "cherry") mixed_tuple = ("Python", 3.12, True) # A tuple with ONE item must have a trailing comma # Otherwise, Python thinks it's just a string in parentheses single_item = ("apple",)
Accessing elements works exactly like it does with lists.
colors = ("red", "green", "blue", "yellow", "purple") print(colors[0]) # Output: red print(colors[-1]) # Output: purple (last item) print(colors[1:4]) # Output: ('green', 'blue', 'yellow')
One of the most powerful features of tuples is "unpacking," where you extract values back into variables.
coordinates = (10, 20, 30) x, y, z = coordinates print(x) # 10 print(y) # 20
While you can't change a tuple, you can combine two tuples to create a new one.
tuple1 = ("a", "b") tuple2 = (1, 2) joined = tuple1 + tuple2 print(joined) # Output: ('a', 'b', 1, 2) multiplied = tuple1 * 2 print(multiplied) # Output: ('a', 'b', 'a', 'b')
Because tuples are immutable, they only have two built-in methods:
| Method | Description | Example |
| count() | Returns the number of times a value appears. | tup.count("apple") |
| index() | Finds the first index of a specific value. | tup.index("banana") |
If you absolutely must change a tuple, the common practice is to convert it to a list, change the list, and convert it back to a tuple.
x = ("apple", "banana", "cherry") y = list(x) # Convert to list y[1] = "kiwi" # Modify x = tuple(y) # Convert back print(x) # ('apple', 'kiwi', 'cherry')
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION