What is a tuple?#
A tuple is an ordered collection, just like a list, but immutable - once created, it cannot be changed. Tuples use round brackets ( ).
point = (10, 20)
rgb = (255, 128, 0)
student = ("Neha", 19, "Bhopal")
empty = ()
Single-item tuples - the comma trap#
(5) is not a tuple - it's just the integer 5 with brackets around it. Always add a trailing comma for one item: (5,).
Accessing items#
Indexing, slicing, len(), in and loops work exactly like lists:
Tuples are immutable#
days[0] = "Monday" # TypeError: 'tuple' object does not support item assignment
days.append("X") # AttributeError: 'tuple' object has no attribute 'append'
To "change" a tuple, create a new one:
Tuple = list जो बदली नहीं जा सकती (read-only list)।
कब इस्तेमाल करें? जब data ऐसा हो जो कभी नहीं बदलना चाहिए - जैसे हफ्ते के दिन, किसी जगह के coordinates (latitude, longitude), या database का एक record। Tuple इस्तेमाल करने से गलती से data बदल जाने का खतरा नहीं रहता, और यह list से थोड़ा तेज़ और कम memory लेता है।
Packing and unpacking#
Packing: putting several values into one tuple. Unpacking: taking them out into separate variables.
You already used unpacking when swapping: a, b = b, a - the right side is packed into a tuple, then unpacked.
Returning multiple values from a function#
Functions often return tuples (you'll write functions soon):
Tuple methods#
Only two, since tuples can't change:
Tuples as dictionary keys#
Because they're immutable, tuples can be keys in a dictionary (lists can't):
List vs tuple#
List [ ] |
Tuple ( ) |
|
|---|---|---|
| Mutable? | Yes | No |
| Methods | many (append, sort...) |
count, index |
| Speed / memory | slightly slower, more memory | slightly faster, less memory |
| Dictionary key? | No | Yes |
| Use for | collections that change | fixed records, constants, return values |
Summary#
- Tuples are ordered and immutable:
(a, b, c). - One-item tuple needs a comma:
(x,). - Indexing, slicing,
len,in, loops work like lists. - Packing/unpacking:
name, age = ("Ravi", 20);first, *rest = t. - Only
count()andindex()methods; can be used as dict keys.