Python Refresher

You can skip if you are familiar with Python already. But take a look at 3. Core Python Data Structures.

What You'll Learn

  • Printing and formatting output
  • Control flow (conditionals, loops)
  • Four essential data structures, and when to use each data structure (Lists, Deques, Dictionaries, Sets)

1. Printing and Output

In interviews, you'll use print() to display results and debug.

Basic Printing

print("www.ChineseCommunity.ai")  # Output: www.ChineseCommunity.ai
print(888)  # Output: 888
print(6.66)  # Output: 6.66

Modern Printing: F-Strings

F-strings let you insert variables directly into strings. They're fast, readable, and the preferred method in Python 3.

Syntax: f"text {variable}"

name = "Jahong"
age = 18

# Simple insertion
print(f"Name: {name}, Age: {age}")  # Output: Name: Jahong, Age: 18

Multiple Values Printing

# Comma adds a space automatically
print("Hello", "World")  # Output: Hello World

# end="" keeps the next print on the same line
print("Hello", end=" ")
print("World")  # Output: Hello World

2. Control Flow

Control flow lets your code make decisions and repeat actions.

If/Else Statements

Use if/elif/else to make decisions based on conditions.

x = 6688

if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

For Loops

For loops iterate over sequences. Here are the three patterns you'll use most in interviews:

Pattern 1: Iterate a specific number of times

# range(5) creates: 0, 1, 2, 3, 4
for i in range(5):
    print(i)  # Prints: 0, 1, 2, 3, 4

Pattern 2: Iterate with both index and value

nums = [10, 20, 30]

# enumerate() gives you both index and value
for i, val in enumerate(nums):
    print(f"Index {i} has value {val}")
# Output:
# Index 0 has value 10
# Index 1 has value 20
# Index 2 has value 30

Pattern 3: Iterate over values only

nums = [10, 20, 30]

for num in nums:
    print(num)  # Prints: 10, 20, 30

While Loops

x = 888

while x > 0:
    print(x)
    x //= 2  # Integer division: divides and rounds down
# Output: 888, 444, 222, 111, 55, 27, 13, 6, 3, 1

3. Core Python Data Structures

Remember we said picking a data structure is like picking the right tool for the question? Here we briefly use Python's core data structures as an example. We'll go deeper later.

Repeat the four data structure templates/tools until they become muscle memory.

  • Lists
  • Deques
  • Dictionaries
  • Sets

Lists (Dynamic Arrays)

What it is: A flexible array that automatically grows and shrinks.

Use when: You need ordered data, stacks, or simple arrays.

# Create a list
arr = [1, 2, 3]

# Add to end (O(1))
arr.append(4)        # arr is now [1, 2, 3, 4]

# Remove from end (O(1))
arr.pop()            # Returns 4, arr is now [1, 2, 3]

# Access by index (O(1))
arr[0] = 888         # arr is now [888, 2, 3]

# Slicing (extremely useful!)
sub = arr[1:3]       # Gets elements at index 1 and 2: [2, 3]
reverse = arr[::-1]  # Reverses the list: [3, 2, 888]

# Print results
print(arr)           # Output: [888, 2, 3]
print(sub)           # Output: [2, 3]
print(reverse)       # Output: [3, 2, 888]

Time Complexity:

OperationComplexityNotes
Access by indexO(1)Fast
Append to endO(1)Fast
Pop from endO(1)Fast
Insert at beginningO(n)Slow

Key Insight: Lists are fast for end operations but slow for front operations.


Deque (Double-Ended Queue)

What it is: A queue that lets you add/remove from both ends efficiently.

Use when: You need BFS (breadth-first search) or sliding window problems.

from collections import deque

# Create a deque
q = deque([1, 2, 3])

# Right end: add and remove (O(1) each)
q.append(4)          # add to right  -> q is [1, 2, 3, 4]
q.pop()              # remove from right -> q is [1, 2, 3], returns 4

# Left end: add and remove (O(1) each) - same idea!
q.appendleft(0)      # add to left  -> q is [0, 1, 2, 3]
q.popleft()          # remove from left -> q is [1, 2, 3], returns 0

# Print final deque
print(list(q))       # Output: [1, 2, 3]

When deque over list?

When you need to add or remove from both ends. Lists are slow when removing from the front (O(n)). Deques are fast for both ends (O(1)).

When to use deque:

  • BFS algorithms (need to remove from front)
  • Sliding window problems
  • Any queue operations

Dictionary (Hash Map)

What it is: Stores key-value pairs. Like a real dictionary: look up a word (key) to find its definition (value).

Use when: You need counting, caching, or O(1) lookups.

# Create a dictionary
counts = {"apple": 3, "banana": 5}

# Insert or update (O(1))
counts["cherry"] = 2  # Adds new key-value pair

# Access (O(1))
print(counts["apple"])  # Output: 3

# Safe access with default value (avoids KeyError)
count = counts.get("orange", 0)  # Returns 0 if "orange" doesn't exist

# Delete (O(1))
del counts["apple"]

# Iterate over key-value pairs
for fruit, count in counts.items():
    print(f"{fruit}: {count}")

Common Pattern: Counting

This pattern shows up in many interview problems:

# Count occurrences of each character
text = "hello"
counts = {}
for char in text:
    counts[char] = counts.get(char, 0) + 1

# Print the result
print(counts)        # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

Key Methods:

  • dict.get(key, default) - Safe access with default value
  • dict.items() - Iterate over key-value pairs
  • dict.keys() - Get all keys
  • dict.values() - Get all values

Set (Hash Set)

What it is: Stores unique elements. No duplicates allowed.

Use when: You need to check if an element is in the set quickly, or remove duplicates.

# Create a set
seen = {1, 2, 3}

# Add element (O(1))
seen.add(4)          # seen is now {1, 2, 3, 4}

# Check if element is in set (O(1)) - Very fast!
if 2 in seen:
    print("Found!")

# Remove element (O(1))
seen.remove(3)       # seen is now {1, 2, 4}

# Common use: Remove duplicates from a list
nums = [1, 2, 2, 3, 3, 3]
unique = list(set(nums))  # [1, 2, 3]

Set vs List:

FeatureSetList
Membership check (in)O(1) FastO(n) Slow
OrderNoYes
DuplicatesNoYes
Use whenFast lookups neededOrder matters

Rule of thumb: Use set when you need to quickly check if an element is in the set. Use list when you need order or duplicates.


Quick Reference Guide

When to Use Each Data Structure

Data StructureUse WhenKey OperationsTime Complexity
ListDefault choice, ordered data, stacksappend(), pop(), [i]O(1) for end ops
DequeNeed to remove from front (BFS, queues)popleft(), appendleft()O(1) for both ends
DictionaryCounting, caching, key-value lookupsget(), items(), [key]O(1) lookups
SetUnique elements, fast 'in set' checkin, add(), remove()O(1) 'in set' check
HaoHaoXueXi - Learn Algorithms with AI