Basic Data Structures
Lists/arrays, dictionaries/maps, sets and tuples, and how to choose between them.
What is it?
A data structure is a way of organizing many values so they're easy and fast to use. Four cover most everyday needs:
- List / array: an ordered sequence, accessed by position (index). Indexes start at 0. Python list, JavaScript Array. - Dictionary / map: key → value pairs. You look values up by key, like a word in a dictionary. Python dict, JavaScript Map or plain objects. - Set: a collection of unique values with fast "is this in here?" checks. Python set, JavaScript Set. - Tuple: a small, fixed, immutable group of values, like a coordinate (x, y). Python has tuple; JavaScript has no tuple type, so a short array is used instead.
Choosing one comes down to how you'll access the data:
- Need order or positions? → list.
- Need to look things up by a name or ID? → dictionary.
- Need uniqueness or fast membership tests? → set.
- A fixed group of related values that shouldn't change? → tuple.
Explain like I'm 10
A list is a numbered queue of people. A dictionary is a phone book: look up a name, get a number. A set is a guest list where each name appears once and the bouncer can instantly say whether you're on it. A tuple is a sealed envelope with a fixed set of items.
Examples
The four structures in Python
fruits = ["apple", "banana", "cherry"] # list
print(fruits[0]) # "apple"
fruits.append("date")
ages = {"ada": 36, "linus": 28} # dict
print(ages["ada"]) # 36
ages["grace"] = 45
tags = {"python", "web", "python"} # set
print(tags) # {'python', 'web'} (duplicates removed)
print("web" in tags) # True
point = (3, 4) # tuple
x, y = point # unpacking
# point[0] = 5 # TypeError: tuples are immutableSquare brackets make lists, curly braces with key: value make dicts, curly braces with plain values make sets, and parentheses make tuples. Note: {} alone is an empty dict; use set() for an empty set.
The same ideas in JavaScript
const fruits = ["apple", "banana", "cherry"];
fruits.push("date");
console.log(fruits.length); // 4
const ages = new Map([["ada", 36], ["linus", 28]]);
ages.set("grace", 45);
console.log(ages.get("ada")); // 36
const user = { name: "Ada", age: 36 }; // object: fixed, known keys
console.log(user.name); // "Ada"
const tags = new Set(["js", "web", "js"]);
console.log(tags.size); // 2
console.log(tags.has("web")); // true
const point = [3, 4]; // array used as a tuple
const [x, y] = point;Use plain objects for records with known fields, and Map for lookups with arbitrary or non-string keys. Use Set to remove duplicates or test membership.
Why choice matters: membership tests
import time
ids_list = list(range(1_000_000))
ids_set = set(ids_list)
start = time.perf_counter()
999_999 in ids_list # scans up to every item: O(n)
print("list:", time.perf_counter() - start)
start = time.perf_counter()
999_999 in ids_set # hash lookup: O(1) on average
print("set: ", time.perf_counter() - start)Checking membership in a list looks at items one by one; a set jumps straight to the right place using a hash. With a million items, the set is typically thousands of times faster.
How it works
Lists/arrays store items in a contiguous block of slots. Reading items[i] is instant (O(1)) because the position can be computed directly. Appending to the end is fast on average; inserting or removing at the front shifts every other item (O(n)). Searching for a value scans item by item (O(n)).
Dictionaries and sets are built on hash tables. A hash function turns a key into a number that picks a slot, so lookup, insert and delete are O(1) on average. Keys must be hashable: in Python, immutable values like strings, numbers and tuples work; lists don't. Python dicts keep insertion order (guaranteed since 3.7); sets have no meaningful order.
Tuples are like lists that can't change. Because they're immutable (and hashable when their contents are), they can be dict keys or set members.
The O(…) notation (Big-O) describes how the work grows as the number of items grows. It's covered in the DSA topics.
list index: 0 1 2
┌────────┬─────────┬─────────┐
│"apple" │"banana" │"cherry" │ access by position: O(1)
└────────┴─────────┴─────────┘ search by value: O(n)
dict "ada" ──hash──► slot 5 ──► 36 lookup by key: O(1) average
"linus" ──hash──► slot 2 ──► 28
set {"python", "web"} (unique; fast "in" checks)
Need… Use
order / position list / array
lookup by key dict / Map / object
uniqueness, "is x in it?" set / Set
fixed group of values tuple (Python) / short array (JS)Why does it exist?
Real programs deal with many values, not one. The way you organize them determines how simple your code is and how fast it runs. Picking the right structure often turns a slow, complicated loop into a single fast lookup.
When to use it
- List: a feed of posts, lines in a file, steps in order, anything you sort or access by position. - Dict/Map: users by ID, settings by name, counting occurrences (word → count), caching results. - Set: removing duplicates, tracking "seen" items, comparing groups (union, intersection, difference). - Tuple: returning multiple values from a function, coordinates, fixed records, dictionary keys made of several parts.
When not to use it
- Don't search a list repeatedly for membership; convert it to a set once. - Don't use a dict when order and position are what matter; use a list. - Don't use a set when you need duplicates or order. - Don't use a plain JavaScript object as a general-purpose map with user-provided keys; keys like "__proto__" can misbehave. Use Map. - For large numeric data, specialized structures (NumPy arrays, typed arrays) are far more efficient than plain lists.
Common mistakes
Forgetting that indexes start at 0, so the last item is
items[len(items) - 1](oritems[-1]in Python).Reading a missing dict key with
d[key], which raisesKeyError. Used.get(key, default)when absence is normal.Writing
{}to create an empty set in Python; it creates an empty dict. Useset().Using
inon a large list inside a loop, making the whole algorithm O(n²). Build a set first.Trying to use a list as a dict key or set member in Python; lists aren't hashable. Use a tuple.
Practice exercises
- Easy:
Given a list of names with duplicates, print the unique names (using a set), then print them in their original order without duplicates.
- Medium:
Count how many times each word appears in a paragraph using a dictionary (Python) or a Map (JavaScript), then print the five most common words.
- Hard:
Given two lists of 100,000 user IDs, find the IDs in both, in only the first, and in only the second. Write a version with nested loops and a version with sets, and time both.
Interview questions
What's the difference between a list and a tuple in Python?
Lists are mutable and meant for variable-length collections of similar items. Tuples are immutable, often used for fixed groups of related values, and can be dict keys or set members if their contents are hashable.
Why is looking up a key in a dictionary fast?
Dictionaries are hash tables: the key's hash determines its slot, so lookup is O(1) on average instead of scanning every entry.
When would you use a set instead of a list?
When you need uniqueness or fast membership checks, or set operations like union and intersection, and don't care about order or duplicates.
What's the time complexity of accessing `items[i]` versus searching for a value in an unsorted list?
Index access is O(1); searching by value is O(n), because each item may need to be checked.
What's the difference between a JavaScript object and a `Map`?
Object keys are strings or symbols and objects inherit prototype properties. Map accepts any key type (including objects), keeps insertion order, has a size property, and is designed for frequent additions and removals.
Why can't a Python list be a dictionary key?
Dict keys must be hashable, and a hash must not change over the key's lifetime. Lists are mutable, so their contents (and hash) could change, so they're unhashable. Use a tuple instead.
Are Python dictionaries ordered?
Yes. Since Python 3.7, dicts are guaranteed to preserve insertion order. Sets are not ordered.
How do you remove duplicates from a list while keeping the original order?
Python: list(dict.fromkeys(items)). JavaScript: [...new Set(items)], since Set preserves insertion order. A plain set(items) in Python loses order.
What does it cost to insert at the front of an array?
O(n): every existing element shifts one slot. If you need fast inserts and removals at both ends, use a deque (collections.deque in Python).
Scenario: a script checks each of 50,000 incoming emails against a list of 50,000 blocked addresses and takes minutes. How do you fix it?
Each in check on a list is O(n), so the total is O(n²). Convert the blocklist to a set once; each check becomes O(1) on average and the script runs in a fraction of a second.