Python List - Summary Notes
Python Tuple - Summary Notes
What is a Tuple?
- A tuple is a collection of ordered, immutable items.
- Tuples are created using parentheses: ()
Properties:
- Ordered: Items have a fixed position.
- Immutable: You cannot change, add, or remove items after creation.
- Allows duplicates and mixed data types.
Creating a Tuple:
my_tuple = (1, 2, 3)
mixed_tuple = (1, "apple", True)
Accessing Elements:
- tuple[0] for the first item
- tuple[-1] for the last item
Tuple with One Item:
- my_tuple = (5,) # Note the comma!
Looping Through Tuples:
for item in my_tuple:
print(item)
Check Existence:
if "apple" in my_tuple:
print("Found")
Length of Tuple:
Python List - Summary Notes
len(my_tuple)
Tuple Methods:
- tuple.count(x): Count how many times x appears
- tuple.index(x): Returns index of first occurrence
Tuple Packing & Unpacking:
- Packing: my_tuple = (1, 2, 3)
- Unpacking: a, b, c = my_tuple
Nested Tuples:
nested = ((1, 2), (3, 4))
print(nested[1][0]) # 3
Why Use Tuples?
- Safer than lists when data should not change
- Can be used as keys in dictionaries (if elements are immutable)
Tuples are useful when you want to store data that should not be modified.