Python Crash Course for DSA

Data Structures & Algorithms · First Steps · Basics · 35 min

Learn the slice of Python you need for interviews: types, the four containers, slicing, loops, comprehensions, functions, and the 'two names, one list' trap.

Every value lives in a box somewhere in memory. A variable is just a luggage tag tied to a box with a string. Two tags can hang off the same box.

The idea in everyday words

Think of a coat check. Your coat (the value) hangs on a rack, and you hold a numbered ticket (the name). If you photocopy your ticket and give it to a friend, there is still only ONE coat. If your friend spills coffee on it, your coat is ruined too. That is aliasing, and it explains most of the 'why did my list change?!' bugs in Python.

Names, values and types

In Python, x = 5 means: make (or find) the value 5, then tie the name x to it. The name is a label, not a box.

If an earlier lesson pictured a variable as a labelled box, that was a good first picture. In Python the more exact picture is a label (a name tag) tied to a value. The value lives somewhere in memory, and the name just points at it. This matters later, when two names point at the same list.

The basic types you will use every day:

Type Example Notes
int 42, -7 whole numbers, no size limit in Python
float 3.14 decimals, can be slightly imprecise
str "hello" text, cannot be changed in place
bool True, False result of comparisons
None None "nothing here yet"

Python is dynamically typed: the value has a type, the name does not. The same name can point at an int now and a string later.

x = 5
print(type(x))
x = "five"
print(type(x))
print(7 // 2, 7 % 2, 7 / 2)   # floor division, remainder, true division

// (floor division) and % (remainder) show up constantly in DSA: middle index, even/odd checks, wrapping around a circle.

The four containers

Almost every interview solution in Python is built from four containers.

A quick word on speed first. The last column of the table uses "Big-O", a short way to say how the work grows as the data grows:

  • O(1): one jump, no matter how big the data is.
  • O(n): walk through all n items once.
  • O(n²): a full walk for EVERY item, so it gets slow very fast.

That is all you need for now. The Big-O lesson later in this module explains it properly.

Container Looks like Ordered? Can change? Duplicates? x in c speed
list [3, 1, 3] yes yes yes slow, O(n)
tuple (3, 1) yes no yes slow, O(n)
dict {"ana": 31} yes (insertion order) yes keys unique fast, O(1)
set {3, 1} no yes no fast, O(1)

How to choose, in one sentence each:

  • list: "I need things in order, by position."
  • dict: "I need to look something up by a key" (name to age, value to index).
  • set: "I only need to know have I seen this?"
  • tuple: "a small fixed group", like a coordinate (row, col). Tuples can be dict keys; lists cannot.

Careful: {} is an empty dict, not an empty set. For an empty set write set(). If you write seen = {} and then seen.add(4), Python stops with AttributeError: 'dict' object has no attribute 'add'.

nums = [3, 1, 4]
nums.append(1)          # add to the end
ages = {"ana": 31}
ages["bo"] = 25         # add or update a key
seen = set()
seen.add(4)
print(nums, ages, 4 in seen, ages.get("zed", 0))

Slicing, loops and comprehensions

Slicing copies a piece of a sequence: a[start:stop:step]. start is included, stop is not.

a = [10, 20, 30, 40, 50]
print(a[1:3])    # [20, 30]
print(a[-1])     # 50, negative index counts from the end
print(a[::-1])   # reversed copy
print(a[:])      # a full copy

Loops you will write in every problem:

words = ["hi", "yo", "hey"]
for w in words:                       # just the items
    print(w)
for i, w in enumerate(words):         # index AND item
    print(i, w)
for i in range(len(words) - 1, -1, -1):  # backwards by index
    print(i)

Inside loops you will often see total += x. It is short for total = total + x: take the old value, add x, and store the result back under the same name. count -= 1 works the same way for taking away.

total = 0
for x in [4, 5, 6]:
    total += x          # same as total = total + x
print(total)            # 15

A comprehension builds a new list in one line: "give me f(x) for each x, if condition".

squares = [x * x for x in range(6) if x % 2 == 0]
lengths = {w: len(w) for w in ["hi", "hey"]}
print(squares, lengths)

Read it out loud left to right and it reads like English. Use it when the loop only builds a collection; use a normal loop when there is more logic.

Functions

A function packages steps behind a name. Inputs go in as parameters, the answer comes out with return. If you forget return, the function gives back None.

def min_max(nums):
    return min(nums), max(nums)   # returns a tuple

lo, hi = min_max([4, 9, 1])       # unpack the tuple
print(lo, hi)

def greet(name, greeting="Hello"):  # default value
    return greeting + ", " + name

print(greet("Ana"), greet("Bo", "Hi"))

Interview challenges are almost always "write a function that takes X and returns Y". Return the answer, don't print it.

One famous trap: never use a mutable default like def f(items=[]). The same list is reused across every call. Use items=None and create the list inside.

Mutability and aliasing: two names, one list

Some objects can be changed in place (mutable: list, dict, set). Others never change (immutable: int, float, str, tuple).

a = [1, 2]
b = a            # NO copy: b is a second tag on the same list
b.append(3)
print(a)         # [1, 2, 3]
print(a is b)    # True: same object

c = a[:]         # a real copy (also list(a) or a.copy())
c.append(99)
print(a, c)
  • == asks "same value?". is asks "same object?".
  • Passing a list to a function passes the same list. If the function appends, the caller sees it.
  • With immutable values the trap disappears: y = x; y += 1 makes a new int and moves y; x is untouched.

The classic grid bug comes from this too:

bad = [[0] * 3] * 2                  # 2 tags on ONE row
bad[0][0] = 7
good = [[0] * 3 for _ in range(2)]   # 2 separate rows
good[0][0] = 7
print(bad, good)

Rule of thumb: if two names might share a mutable object, and one of them changes it, both will see the change.

Step by step

  1. a = [1, 2]:

    Python creates a list object holding 1 and 2, and ties the name a to it.

  2. b = a:

    No new list is made. The name b is tied to the SAME list. id(a) == id(b).

  3. b.append(3):

    append changes the object in place. The one list now holds [1, 2, 3].

  4. print(a):

    a points at that same list, so it prints [1, 2, 3] even though we never touched a by name.

  5. c = a[:]:

    Slicing builds a brand-new list [1, 2, 3]. c is tied to the new one. a is c is False.

  6. c.append(99):

    Only the copy changes: c is [1, 2, 3, 99], a stays [1, 2, 3].

Code example

nums = [3, 1, 4]
nums.append(1)
print("list:", nums, "first two:", nums[:2], "reversed:", nums[::-1])

ages = {"ana": 31, "bo": 25}
ages["cy"] = 40
for name, age in ages.items():
    print(name, "is", age)

print("unique sorted:", sorted(set(nums)))
print("even squares:", [x * x for x in range(6) if x % 2 == 0])

a = [1, 2]
b = a              # alias: same list
b.append(3)
print("a after b.append(3):", a, "| a is b:", a is b)

c = a[:]           # copy: new list
c.append(99)
print("a after c.append(99):", a, "| c:", c, "| a is c:", a is c)

Complexity

  • Time: list index / append: O(1). `x in list`, insert(0, x), pop(0): O(n). dict and set lookups: O(1) on average.
  • Space: A slice or comprehension builds a new list: O(k) extra for k items. An alias (b = a) costs nothing because nothing is copied.

Interview tips

  • Say which container you are choosing and why: 'I'll use a set so the membership check is O(1).' Interviewers listen for that reasoning.

  • Know the hidden costs: x in list, list.insert(0, x), list.pop(0) and s += char in a loop are all linear. Use a set, deque or ''.join instead.

  • If you modify an input list, say so out loud, or copy it first. Surprising the caller is a classic bug.

  • Use enumerate when you need the index and the value; it reads cleaner than range(len(a)).

Challenge: Remove Duplicates, Keep the Order

Given a list of integers, return a new list where each value appears only once: keep its first appearance and preserve the original order.

Example: dedupe_keep_order([3, 1, 3, 2, 1]) → [3, 1, 2]

Aim for one pass, O(n) time. One test uses about three million numbers, so the slow x in out check will run out of time there.

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in First Steps

Previous: Think Like a Programmer · Next: Functions, Lists & Strings