A Tuple is a data structure very similar to a List, but with one major difference: it is immutable. This means once you create a tuple, you cannot change, add or remove its elements.
Key Characteristics
Ordered: Tuples keep the order in which you first defined them.
Immutable: You cannot modify them after creation (no appending or deleting).
Allows Duplicates: You can have the same item multiple times.
Heterogeneous: You can mix different types of data (strings, numbers, objects) in the same tuple.
Creating a Tuple
Tuples are created using parentheses(), with items separated by commas.
# Creating a tuple my_tuple= ("apple", "banana", "cherry")
# Parentheses are actually optional, but recommended for readability another_tuple="red", "green", "blue"
The “Single Element” Rule
This is a common mistake for beginners! If you want a tuple with only one item, you must include a trailing comma. Without it, Python will just see it as a regular variable (like a string or integer).
# WRONG: This is just a string not_a_tuple= ("apple")
# RIGHT: This is a tuple is_a_tuple= ("apple",)
Why Use a Tuple?
You use a Tuple when you want to ensure the data in your program stays the same.
Safety: It prevents accidental changes to data that should remain constant (like the coordinates of a location or days of the week).
Performance: Because they are “locked,” Tuples are slightly faster and use less memory than Lists.
List vs. Tuple: Quick Comparison
Feature
List []
Tuple ()
Changeable?
Yes (Mutable)
No (Immutable)
Speed
Slower
Faster
Memory
Uses more memory
Uses less memory
Common Use
Items that change often
“Read-only” data
Accessing Tuple Items
Just like Lists, Tuples use indexing. The first item starts at index 0.
planets= ("Mercury", "Venus", "Earth", "Mars") print(planets[0]) # Output: Mercury print(planets[-1]) # Output: Mars (The last item)