šŸ

Tuples and Sets

Beginner
80 XP
35 min
Lesson Content

Tuples and Sets: More Data Structures

Python has several built-in data structures. Let's explore tuples and sets, which have different use cases than lists.

Tuples

Tuples are ordered, immutable collections. Once created, they cannot be changed.

# Creating tuples
coordinates = (10, 20)
point = 10, 20  # Parentheses optional

# Single item tuple (needs comma) single = (5,) # Not (5) which is just a number
# Accessing items (like lists) print(coordinates[0]) # 10 print(coordinates[1]) # 20
# Tuples are immutable (cannot change) # coordinates[0] = 5 # Error!

Tuple Operations

tuple1 = (1, 2, 3)
tuple2 = (4, 5)

# Concatenation combined = tuple1 + tuple2 # (1, 2, 3, 4, 5)
# Repetition repeated = tuple1 * 2 # (1, 2, 3, 1, 2, 3)
# Unpacking x, y = (10, 20) # x = 10, y = 20
# Length print(len(tuple1)) # 3

When to Use Tuples

  • āœ… Coordinates (x, y)
  • āœ… RGB colors (255, 0, 0)
  • āœ… Database records
  • āœ… When you want to prevent accidental changes

Sets

Sets are unordered collections of unique items. No duplicates allowed!

# Creating sets
fruits = {"apple", "banana", "orange"}
numbers = {1, 2, 3, 4, 5}

# Empty set (not {}) empty = set() # {} creates a dictionary!
# Sets automatically remove duplicates unique = {1, 2, 2, 3, 3, 3} # {1, 2, 3}

Set Operations

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Add item set1.add(5) # {1, 2, 3, 4, 5}
# Remove item set1.remove(5) # {1, 2, 3, 4} set1.discard(10) # No error if not found
# Union (all items from both) union = set1 | set2 # {1, 2, 3, 4, 5, 6} union = set1.union(set2)
# Intersection (common items) intersection = set1 & set2 # {3, 4} intersection = set1.intersection(set2)
# Difference (items in set1 but not set2) diff = set1 - set2 # {1, 2} diff = set1.difference(set2)

Set Methods

numbers = {1, 2, 3}

# Check membership (very fast!) print(2 in numbers) # True
# Length print(len(numbers)) # 3
# Clear all items numbers.clear() # set()

When to Use Sets

  • āœ… Remove duplicates from a list
  • āœ… Fast membership testing
  • āœ… Mathematical set operations
  • āœ… Tracking unique items

Converting Between Types

# List to tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)  # (1, 2, 3)

# List to set (removes duplicates) my_list = [1, 2, 2, 3, 3] my_set = set(my_list) # {1, 2, 3}
# Set to list my_list = list(my_set) # [1, 2, 3]
Example Code

Practice using tuples and sets.

# Create a tuple for coordinates
point = (10, 20)

# Unpack the tuple
x, y = point
print(f"X: {x}, Y: {y}")

# Create a set of unique numbers
numbers = {1, 2, 3, 4, 5}

# Add a number
numbers.add(6)
print(f"Numbers: {numbers}")

# Check if 3 is in the set
print(f"3 in set: {3 in numbers}")

Expected Output:

X: 10, Y: 20
Numbers: {1, 2, 3, 4, 5, 6}
3 in set: True
Study Tips
  • •Read the theory content thoroughly before practicing
  • •Review the example code to understand key concepts
  • •Proceed to the Practice tab when you're ready to code