Python Collections

Lists, Tuples, Sets & Dictionaries

Master Python's collection data structures — essential for DSA, data manipulation, and real-world applications.

Python 3 ✓ DSA Foundation 4 Topics O(1) Lookups
01

Lists in Python

A list is an ordered, mutable collection. Lists power searching, sorting, stacks, queues, matrices, and graph representations in DSA.

Python — Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[0])    # apple
print(fruits[-1])   # cherry  (negative indexing)

# Slicing: list[start:end:step]
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])    # [2, 3, 4]
print(numbers[::2])    # [0, 2, 4, 6, 8]
print(numbers[::-1])   # reversed

# List comprehension
squares = [x**2 for x in range(5)]   # [0, 1, 4, 9, 16]
evens   = [x for x in range(10) if x % 2 == 0]

# 2D List (matrix)
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix[1][2])    # 6
copy() matters! list2 = list1 makes both point to the same object. Use list1.copy() for an independent copy.
02

Tuples in Python

A tuple is an ordered, immutable collection. Once created, values cannot be modified — making tuples safe, faster than lists, and ideal for fixed data.

FeatureListTuple
Mutable✓ Yes✗ No
Syntax[ ]( )
PerformanceSlowerFaster
MethodsManyOnly count(), index()
Single-element tuple needs a trailing comma: (5,) — without it, (5) is just an integer!
03

Sets in Python

A set is an unordered collection of unique elements. Blazing-fast membership testing (O(1) avg) and mathematical operations.

Python — Sets
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)   # Union:        {1,2,3,4,5}
print(a & b)   # Intersection: {3}
print(a - b)   # Difference:   {1,2}
print(a ^ b)   # Sym. Diff:    {1,2,4,5}

# IMPORTANT: empty set must use set()
s = {}         # ✗ Creates an empty DICT
s = set()      # ✓ Creates an empty SET
04

Dictionaries in Python

A dictionary stores data as key→value pairs. The backbone of hash tables — offering O(1) average lookup for frequency counting, memoization, and adjacency lists.

Python — Dictionaries
student = {"name": "Alice", "age": 20, "marks": 85}

student.get("salary")    # None (safe access)
student["grade"] = "A"  # add key
student.pop("age")        # remove key

for key, value in student.items():
    print(key, ":", value)

# Dict comprehension
squares = {x: x**2 for x in range(5)}

Quick Quiz

1. defaultdict avoids…
2. deque is optimized for…
3. Counter most directly…
4. namedtuple gives…
5. dict vs set — set stores…