Python Fundamentals & Data Structures
Lists, dicts, sets, tuples, comprehensions, and the core Python idioms every data scientist uses daily.
In plain words
Lists keep things in order, dicts look things up by name, sets keep only one of each, and tuples can't be changed.
Think of it like…
A kitchen: a list is a queue of orders in the sequence they arrived, a tuple is a printed recipe card you don't edit, a dict is the labelled spice rack where you grab by name, and a set is the box of unique ingredients where you only ask "do we have it?".
Where you’ve seen it
A data scientist has 2 million order IDs and a list of 50,000 flagged IDs. [o for o in orders if o in flagged_list] takes minutes because each check scans 50,000 items; converting flagged = set(flagged_list) first makes the same line run in about a second, because set membership is a hash lookup.
Words you’ll hear
- Mutability
- Whether an object can be changed in place; lists, dicts and sets can, tuples and strings can't.
- Hashable
- Immutable, comparable objects that can be dict keys or set members.
- Comprehension
- A compact expression that builds a list, dict or set from an iterable.
- Reference
- A variable name pointing at an object; assignment copies the pointer, not the object.
Visual diagram
Theory & deep dive
The four containers and comprehensions
Lists support indexing, slicing (a[1:4]), append and in-place sorting; tuples are the fixed version, handy for returning several values or as dict keys. Dicts keep insertion order in modern Python and offer get with a default (d.get("k", 0)), items() for loops and setdefault or defaultdict for grouping. Sets provide union (|), intersection (&) and difference (-) in one operator.
Comprehensions combine a loop and a filter: {name: len(name) for name in names} builds a dict, {x % 10 for x in ids} a set. They're usually clearer and faster than appending in a loop, but stop at one loop and one condition; anything more complex deserves a normal loop with a name. Generator expressions, written with parentheses, produce items lazily and avoid building a big list when you only need a sum or a membership test.
counts = {} then for city in cities: counts[city] = counts.get(city, 0) + 1. The same result in one line is collections.Counter(cities), and counts.most_common(3) returns the top three.
Mutability and the copy trap
A variable is a name bound to an object. b = a makes both names point at the same list, so b.append(1) also changes a. A shallow copy (a.copy(), list(a), a[:]) creates a new outer list but shares nested objects, so a list of lists still shares its inner lists; copy.deepcopy(a) copies everything. Default arguments follow the same rule: def f(x, acc=[]) reuses one list across calls, a classic bug; use acc=None and create the list inside.
Immutability is useful, not limiting: tuples and frozensets can be dictionary keys, strings are safe to share, and immutable data can't be changed by accident in a long pipeline. When a function shouldn't alter its input, either copy it first or build and return a new object.
def add(item, bucket=[]): bucket.append(item); return bucket called twice returns [1] then [1, 2], because bucket is created once. The fix: def add(item, bucket=None): bucket = [] if bucket is None else bucket.
How it works, step by step
Step 1 of 41. State the access pattern
Decide whether you mostly iterate in order, look up by key, test membership or keep unique values.
- Question
- decides structure
When to use it & trade-offs
What it is
Four built-in containers cover most data work: a list is an ordered, changeable sequence; a tuple is ordered but fixed; a dict maps keys to values with fast lookup; a set holds unique items with fast membership tests. Comprehensions build them in one readable line: [x * 2 for x in nums if x > 0]. Understanding mutability (lists, dicts and sets change in place; tuples, strings and numbers don't) explains most beginner bugs.
Why it matters: Pandas, NumPy and scikit-learn are built on these basics, and interview screens still test them: counting items with a dict, de-duplicating with a set, reshaping records with a comprehension. Picking the right container also decides speed: checking x in my_list scans every element, while x in my_set is close to constant time, which matters when you filter millions of rows.
When to reach for it
- Sets for de-duplication and fast filtering by ID
- Dicts for counts, lookups and mappings
- Comprehensions for short transformations
When to avoid or be careful
- Repeated
inchecks on a large list - Mutable default arguments
- Comprehensions with several nested loops and conditions
Python containers compared
Strengths: Indexing, slicing, sorting; the default sequence.
Watch out: Membership and removal by value are O(n).
Strengths: Average O(1) get and set; keeps insertion order.
Watch out: Keys must be hashable; uses more memory than a list.
Strengths: Set algebra and fast membership; tuples are hashable and safe.
Watch out: Sets are unordered; tuples can't be changed.
Interview signals & numbers to know
When this topic comes up
- “Count occurrences of each item”
- “Remove duplicates but keep order”
- “Why did my original list change?”
- Big-O of membership tests
- Dict vs list lookup
Benchmarks & rules of thumb
- O(1) vs O(n)
- set/dict lookup vs list search
- Python 3.7+
- dicts preserve insertion order
- 0
- index of the first element
Common mistakes & follow-ups
Common interview mistakes
- Using a list of 50,000 IDs for repeated
inchecks inside a loop over millions of rows. - Writing
b = aand expecting an independent copy. - Using
acc=[]as a default argument and accumulating results across calls.
Likely interviewer follow-ups
- How would you de-duplicate a list while keeping the order?
- What's the difference between a shallow and a deep copy?
- Why can a tuple be a dict key but a list can't?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Python Fundamentals & Data Structures with data science interview Q&A and hands-on practice.