Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 1/ 160
01. Python & Data Wrangling

Python Fundamentals & Data Structures

Lists, dicts, sets, tuples, comprehensions, and the core Python idioms every data scientist uses daily.

BeginnerLists & Dicts · Comprehensions3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Counting and grouping with a dict

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.

Key takeaway: Dicts and sets for lookup, lists for order, comprehensions to build them clearly.

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.

The shared default list bug

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.

Key takeaway: Assignment shares objects; copy deliberately and avoid mutable default arguments.

How it works, step by step

Step 1 of 4
Design

1. State the access pattern

Decide whether you mostly iterate in order, look up by key, test membership or keep unique values.

membership test → set · lookup → dict · order → list
Key numbers at this step
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 in checks on a large list
  • Mutable default arguments
  • Comprehensions with several nested loops and conditions

Python containers compared

list
Best for: Ordered, changeable collections and stacks

Strengths: Indexing, slicing, sorting; the default sequence.

Watch out: Membership and removal by value are O(n).

dict
Best for: Lookups, counting and grouping by key

Strengths: Average O(1) get and set; keeps insertion order.

Watch out: Keys must be hashable; uses more memory than a list.

set / tuple
Best for: Unique items and membership / fixed records

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 in checks inside a loop over millions of rows.
  • Writing b = a and 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?
Interview tip: When asked to speed up a loop, look for a list used for membership tests. Converting it to a set is the most common one-line win.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Python Fundamentals & Data Structures with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Next topic
Functions, Modules & OOP Basics