πΉ What are Tuples?
β’ Tuples are ordered and immutable collections.
β’ They can store multiple items like lists, but unlike lists, they cannot be modified (no append, remove, etc.).
β’ Defined using parentheses ().
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # apple
πΉ Key Properties of Tuples
β
Ordered β items have a fixed sequence
β
Immutable β canβt change once created
β
Allow duplicates β can store repeated values
β
Can store mixed data types
πΉ Why Use Tuples?
β’ Safer than lists if data shouldnβt change
β’ Faster than lists (performance benefit)
β’ Can be used as dictionary keys (since immutable)
π Tuple Operations & Examples
Accessing Elements
numbers = (10, 20, 30, 40)
print(numbers[1]) # 20
Tuple Packing & Unpacking
person = ("Alice", 25, "Engineer")
name, age, profession = person
print(name) # Alice
Concatenation & Repetition
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # (1, 2, 3, 4)
print(t1 * 2) # (1, 2, 1, 2)
Nesting Tuples
nested = (1, (2, 3), (4, 5))
print(nested[1][1]) # 3
π― Reflection
Tuples may look similar to lists, but their immutability makes them useful in situations where data must remain constant.
β‘ Next, Iβll be diving into Sets and Set operations in Python!
Top comments (0)