Menu

Lists, Tuples, and Sets

Introduction

Python has several built-in collection types. In this lesson, we'll cover lists (mutable, ordered), tuples (immutable, ordered), and sets (mutable, unordered, unique elements).

Lists

Lists are Python's most versatile data structure — ordered, mutable, and can hold mixed types.

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]

# Accessing elements
fruits[0]     # "apple"
fruits[-1]    # "cherry" (last element)
fruits[1:3]   # ["banana", "cherry"] (slicing)

# Modifying
fruits.append("date")
fruits.insert(1, "blueberry")
fruits.remove("banana")
popped = fruits.pop()  # removes and returns last item

# List comprehensions (very Pythonic!)
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

# Useful methods
len(fruits)           # length
sorted(numbers)       # returns sorted copy
numbers.sort()        # sorts in place
numbers.reverse()     # reverses in place
3 in numbers          # True (membership check)

Tuples

# Tuples are immutable lists
coordinates = (10, 20)
rgb = (255, 128, 0)

x, y = coordinates  # tuple unpacking

# Single-element tuple needs a comma
single = (42,)  # not (42)

Sets

# Sets: unordered, unique elements
unique_nums = {1, 2, 3, 3, 4}  # {1, 2, 3, 4}

a = {1, 2, 3}
b = {3, 4, 5}
a | b   # {1, 2, 3, 4, 5} (union)
a & b   # {3} (intersection)
a - b   # {1, 2} (difference)

Assignment

  1. Read about Python data structures.
  2. Practice list comprehensions — create a list of all odd numbers from 1 to 50.
  3. Experiment with set operations to find common elements between two lists.

Knowledge check

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!