Python Data Structures
Python Tuples
A tuple is an ordered collection like a list, but once created it cannot be changed — that immutability makes tuples fast and safe to share around your code.
Creating a Tuple
You create a tuple with comma-separated values, usually inside parentheses. Tuples can hold mixed data types just like lists.
point = (3, 4)
person = ("Riya", 22, "Pune")
print(point, person)Tuples Are Immutable
Once a tuple is created, you cannot add, remove, or reassign its items. Trying to do so raises a TypeError — this guarantees the data stays constant, which is useful for things like coordinates or fixed configuration values.
point = (3, 4)
point[0] = 9 # TypeError: 'tuple' object does not support item assignmentPacking and Unpacking
Packing groups several values into one tuple; unpacking does the reverse, assigning each tuple item to its own variable in one line. This pattern is common when a function returns multiple values.
person = "Riya", 22, "Pune" # packing (parentheses optional)
name, age, city = person # unpacking
print(name, age, city)Tuples vs Lists
| Feature | Tuple | List |
|---|---|---|
| Syntax | (1, 2, 3) | [1, 2, 3] |
| Mutable | No | Yes |
| Speed | Slightly faster | Slightly slower |
| Use case | Fixed data, dictionary keys | Data that changes often |
Single-Element Tuples
A common trap: (5) is just the number 5 in parentheses, not a tuple. You must add a trailing comma to make Python treat it as a one-item tuple.
not_a_tuple = (5)
print(type(not_a_tuple)) # <class 'int'>
single = (5,)
print(type(single)) # <class 'tuple'>Because tuples are immutable, they can be used as keys in a dictionary or stored in a set — lists cannot.
