Lists, Tuples & Sets

Difficulty: Beginner

Question

Compare lists, tuples, and sets. When would you use each?

Answer

Lists, tuples, and sets are all collection types but serve different purposes:

- List: Ordered, mutable, allows duplicates. Use for collections that change. - Tuple: Ordered, immutable, allows duplicates. Use for fixed data, dict keys, function returns. - Set: Unordered, mutable, no duplicates. Use for membership testing, removing duplicates, set math.

Performance: Set membership check is O(1) vs list O(n). Tuples are slightly faster than lists and use less memory.

Code examples

List Operations

# Creating and modifying lists
nums = [3, 1, 4, 1, 5, 9, 2, 6]

nums.append(7)         # Add to end
nums.insert(0, 0)      # Insert at index
nums.extend([8, 10])   # Add multiple
nums.remove(1)         # Remove first occurrence
popped = nums.pop()   # Remove & return last
print(nums)

# Sorting
nums.sort()               # In-place sort
print(nums)
print(sorted(nums, reverse=True))  # Returns new sorted list

# List as stack (LIFO)
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print(stack.pop())  # 'c'
print(stack)        # ['a', 'b']

Lists are the workhorse collection. sort() modifies in-place (returns None), sorted() returns a new list.

Tuples: Immutable Records

# Tuples as fixed records
point = (3, 4)
rgb = (255, 128, 0)
person = ("Alice", 30, "Engineer")

# Unpacking
x, y = point
name, age, role = person
print(f"{name} is {age}, works as {role}")

# Swap without temp variable
a, b = 1, 2
a, b = b, a  # Tuple unpacking!
print(a, b)  # 2 1

# Tuples as dict keys (lists can't be)
locations = {
    (40.7, -74.0): "New York",
    (51.5, -0.1): "London",
}
print(locations[(40.7, -74.0)])  # 'New York'

# Named tuples for clarity
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y)  # 3 4

Tuples are perfect for fixed collections of items. Their immutability makes them hashable, so they can be dictionary keys.

Sets: Unique Collections & Set Math

# Remove duplicates
nums = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(nums))
print(unique)  # [1, 2, 3, 4]

# Set operations
backend = {'Python', 'Java', 'Go', 'Rust'}
frontend = {'JavaScript', 'TypeScript', 'Python'}

print(backend & frontend)   # Intersection: {'Python'}
print(backend | frontend)   # Union: all languages
print(backend - frontend)   # Difference: {'Java', 'Go', 'Rust'}
print(backend ^ frontend)   # Symmetric diff: in one but not both

# O(1) membership testing
big_list = list(range(1_000_000))
big_set = set(range(1_000_000))

import time
start = time.time()
999_999 in big_list  # O(n) - slow
print(f"List: {time.time() - start:.6f}s")

start = time.time()
999_999 in big_set   # O(1) - fast
print(f"Set: {time.time() - start:.6f}s")

Sets use hash tables internally, giving O(1) average lookup time. This makes them ideal for membership testing and deduplication.

Key points

Concepts covered

Lists, Tuples, Sets, Mutability, Operations