Python Lists, Tuples, Dictionaries and Sets Explained with Examples
P4.2 Python Tuples: When to Use a Tuple Instead of a List
Why. Some values should never change, like a GPS location or the (year, month) of a report. A tuple protects them.
What. A tuple uses round brackets (). You can read it, but you cannot change it. You can also "unpack" it into separate variables.
How.
Use a tuple
- Create it with
(). - Read items by index.
- Unpack:
a, b = my_tuple.
Worked example A — Store a location.
Step 1 — What we do. A delivery hub in Dubai has a fixed latitude and longitude.
Step 2 — Type and run this code.
hub = (25.2048, 55.2708)
print(hub[0])
print(hub[1])
Step 3 — Output you should see.
25.2048
55.2708
Step 4 — What it means. Reading works like a list. The values stay safe.
Worked example B — Unpack a tuple.
Step 1 — What we do. We split the location into two named variables.
Step 2 — Type and run this code.
hub = (25.2048, 55.2708)
lat, lon = hub
print("Lat:", lat, "Lon:", lon)
Step 3 — Output you should see.
Lat: 25.2048 Lon: 55.2708
Step 4 — What it means. Unpacking gives each value a clear name. You will see this when loops give two values at once.
Worked example C — An intended error: tuples cannot change.
Step 1 — What we do. We try to change the latitude.
Step 2 — Type and run this code.
hub = (25.2048, 55.2708)
hub[0] = 26.0
Step 3 — Output you should see.
TypeError: 'tuple' object does not support item assignment
Step 4 — What it means. Python stops us. That is the point of a tuple: fixed data stays fixed. pandas df.shape also returns a tuple like (100, 5).
Ravindra Bagale's Tip
When a function returns two values, Python gives you a tuple. rows, cols = df.shape is the most common example in pandas.
Ravindra Bagale's Tip – मराठी
Function दोन values return करतं तेव्हा Python tuple देतो. pandas मधलं सर्वात सामान्य उदाहरण rows, cols = df.shape.
Ravindra Bagale's Tip – हिंदी
Function दो values return करे तो Python tuple देता है. pandas का सबसे आम उदाहरण rows, cols = df.shape.