06

Day 6: Tuples and Sets

Chapter 6 • Beginner

30 min

Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable.

Tuple Properties:

  • Ordered (items have a defined order)
  • Unchangeable (cannot modify after creation)
  • Allow duplicate values
  • Indexed (can access items by index)
  • Immutable

Sets are used to store multiple items in a single variable. A set is a collection which is unordered, unchangeable, and unindexed.

Set Properties:

  • Unordered (no defined order)
  • Unchangeable (cannot modify items)
  • No duplicate values
  • Unindexed (cannot access by index)
  • Mutable (can add/remove items)

Hands-on Examples

Tuples and Sets

# Tuples
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_item = (42,)  # Note the comma

print("Coordinates:", coordinates)
print("First color:", colors[0])
print("Single item:", single_item)

# Tuple methods
print("Count of 'red':", colors.count("red"))
print("Index of 'green':", colors.index("green"))

# Sets
fruits = {"apple", "banana", "cherry", "apple"}  # Duplicate removed
numbers = {1, 2, 3, 4, 5}

print("Fruits set:", fruits)
print("Numbers set:", numbers)

# Set operations
fruits.add("orange")
fruits.remove("banana")
print("After modifications:", fruits)

Tuples are immutable while sets are mutable but unordered and contain unique elements.