Chapter 6: Data Structures / Lesson 34

Tuples

Introduction to Tuples

Tuples are immutable sequences in Python, similar to lists but with one key difference: they cannot be modified after creation. Tuples are perfect for storing fixed collections of data that shouldn't change, such as coordinates, RGB color values, or database records.

Tuples are more memory-efficient than lists and can be used as dictionary keys (since they're immutable), making them useful in many scenarios.

Creating Tuples

Tuples are created using parentheses () with items separated by commas. You can also create a tuple with just a comma (parentheses are optional in some cases):

creating_tuples.py
# Tuple with parentheses coordinates = (10, 20) print(coordinates) # (10, 20) # Tuple without parentheses (comma makes it a tuple) point = 5, 10 print(point) # (5, 10) # Single item tuple (note the comma!) single = (42,) print(single) # (42,) # Empty tuple empty = () print(empty) # () # Tuple with mixed types person = ("Alice", 25, 5.6) print(person) # ('Alice', 25, 5.6)

Accessing Tuple Items

You access tuple items the same way as lists, using indexing and slicing:

accessing_tuples.py
# Access by index colors = ("red", "green", "blue") print(colors[0]) # red print(colors[1]) # green # Negative indexing print(colors[-1]) # blue # Slicing print(colors[1:]) # ('green', 'blue') # Tuple unpacking x, y = (10, 20) print(x) # 10 print(y) # 20 # Multiple assignment name, age, height = ("Bob", 30, 6.0) print(name, age, height)

Tuple Methods

Tuples have only two methods since they're immutable: count() and index():

tuple_methods.py
# count() - counts occurrences numbers = (1, 2, 2, 3, 2) print(numbers.count(2)) # 3 # index() - finds first occurrence fruits = ("apple", "banana", "cherry") idx = fruits.index("banana") print(idx) # 1 # Other operations print(len(fruits)) # 3 print("apple" in fruits) # True print("orange" not in fruits) # True

When to Use Tuples

✅ Use Tuples When:

• Data should not change (immutable)

• You need a dictionary key (tuples are hashable)

• Returning multiple values from a function

• Memory efficiency matters (tuples use less memory)

• Data integrity is important (prevents accidental modification)

💡 Use Lists When:

• You need to modify the collection

• You need list methods (append, remove, etc.)

• Order might change

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...