7/20
Lists & Tuples Β· Page 2 of 2

Tuples & When to Use Them

Tuples β€” Immutable Sequences

A tuple is like a list but immutable β€” once created, it cannot be changed. Use tuples for data that should not be modified.

coordinates = (40.7128, -74.0060)  # New York lat/lon
rgb_red = (255, 0, 0)

List vs Tuple β€” When to Use Which?

ListTuple
Syntax[1, 2, 3](1, 2, 3)
Mutableβœ… Yes❌ No
Use forChanging dataFixed records
PerformanceSlightly slowerFaster
Hashable❌ Noβœ… Yes

Tuple Unpacking

One of Python's most elegant features:

point = (10, 20)
x, y = point  # x=10, y=20

# Swap variables without temp
a, b = 5, 10
a, b = b, a   # a=10, b=5

Named Tuples

For readability, use collections.namedtuple:

from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x, p.y)  # 10 20
main.py
Loading...
OUTPUT
β–ΆClick "Run Code" to execute…