"Python's data structures are your toolbox. Master them and you master the language."
- Lists
- Tuples
- Sets
- Dictionaries
- Indexing & Slicing
- List Comprehension
- Nested Structures
- Shallow Copy vs Deep Copy
- Packing & Unpacking
- Quick Comparison Table
- Interview Q&A
| Feature | List | Tuple | Set | Dict |
|---|---|---|---|---|
| Ordered | ✅ | ✅ | ❌ | ✅ (3.7+) |
| Mutable | ✅ | ❌ | ✅ | ✅ |
| Duplicates | ✅ | ✅ | ❌ | Keys: ❌ Values: ✅ |
| Indexed | ✅ | ✅ | ❌ | By key |
| Syntax | [1,2] |
(1,2) |
{1,2} |
{"k":v} |
| Use Case | General collection | Fixed data | Unique items, Math ops | Key-value mapping |
A list is an ordered, mutable, indexed collection that allows duplicates.
# Empty list
empty = []
empty2 = list()
# With elements
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, None] # lists can hold ANY types
nested = [[1, 2], [3, 4], [5, 6]] # nested lists
# From other iterables
from_string = list("hello") # ['h', 'e', 'l', 'l', 'o']
from_range = list(range(1, 6)) # [1, 2, 3, 4, 5]
from_tuple = list((1, 2, 3)) # [1, 2, 3]fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Positive indexing (0-based)
print(fruits[0]) # apple
print(fruits[2]) # cherry
# Negative indexing (from the end)
print(fruits[-1]) # elderberry
print(fruits[-2]) # date
# Slicing [start:stop:step]
print(fruits[1:4]) # ['banana', 'cherry', 'date']
print(fruits[:3]) # ['apple', 'banana', 'cherry']
print(fruits[2:]) # ['cherry', 'date', 'elderberry']
print(fruits[::2]) # ['apple', 'cherry', 'elderberry'] (every 2nd)
print(fruits[::-1]) # Reverse: ['elderberry', 'date', 'cherry', 'banana', 'apple']nums = [1, 2, 3, 4, 5]
# append() — add to end ← O(1)
nums.append(6) # [1, 2, 3, 4, 5, 6]
# insert() — add at index ← O(n)
nums.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
# extend() — add multiple items
nums.extend([7, 8, 9]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# + concatenation — creates NEW list
new = [1, 2] + [3, 4] # [1, 2, 3, 4]
# Repetition
print([0] * 5) # [0, 0, 0, 0, 0]
# Change element
nums[0] = 100 # [100, 1, 2, ...]
# Slice assignment
nums[1:3] = [10, 20] # Replace elements 1-2fruits = ["apple", "banana", "cherry", "banana"]
# remove() — removes FIRST occurrence by value ← O(n)
fruits.remove("banana") # ['apple', 'cherry', 'banana']
# pop() — removes by index, returns the element ← O(1) for last
last = fruits.pop() # removes 'banana', returns it
first = fruits.pop(0) # removes 'apple' (index 0)
# del — remove by index or slice
my_list = [10, 20, 30, 40, 50]
del my_list[1] # [10, 30, 40, 50]
del my_list[1:3] # [10, 50]
# clear() — empty the list
fruits.clear() # []nums = [3, 1, 4, 1, 5, 9, 2, 6]
# Searching
print(nums.index(5)) # 4 (first occurrence)
print(nums.count(1)) # 2 (how many times 1 appears)
# Sorting
nums.sort() # In-place sort: [1, 1, 2, 3, 4, 5, 6, 9]
nums.sort(reverse=True) # Descending: [9, 6, 5, 4, 3, 2, 1, 1]
# sorted() — returns a NEW sorted list (original unchanged)
original = [3, 1, 4, 1, 5]
sorted_copy = sorted(original) # [1, 1, 3, 4, 5]
print(original) # [3, 1, 4, 1, 5] — unchanged!
# sort with key
words = ["banana", "fig", "apple", "cherry"]
words.sort(key=len) # Sort by length: ['fig', 'apple', 'banana', 'cherry']
words.sort(key=lambda w: w[-1]) # Sort by last character
# reverse()
nums = [1, 2, 3, 4, 5]
nums.reverse() # [5, 4, 3, 2, 1]
# copy() — shallow copy
copy = nums.copy()A tuple is an ordered, immutable, indexed collection that allows duplicates. Use tuples for data that should not change.
# Empty tuple
empty = ()
empty2 = tuple()
# With elements
point = (3, 4)
rgb = (255, 128, 0)
single = (42,) # ⚠️ Trailing comma required for single-element tuple!
# not_tuple = (42) # This is just an int with parentheses!
# Without parentheses (Python allows this)
coords = 10, 20, 30 # This is a tuple!
print(type(coords)) # <class 'tuple'># 1. Tuples are FASTER than lists (no overhead of mutability)
import timeit
list_time = timeit.timeit("[1, 2, 3, 4, 5]", number=1_000_000)
tuple_time = timeit.timeit("(1, 2, 3, 4, 5)", number=1_000_000)
print(f"List: {list_time:.3f}s | Tuple: {tuple_time:.3f}s")
# Tuple is ~3x faster to create
# 2. Tuples can be used as DICTIONARY KEYS (lists cannot — not hashable)
locations = {
(40.7128, -74.0060): "New York",
(51.5074, -0.1278): "London",
}
print(locations[(40.7128, -74.0060)]) # New York
# 3. Tuples signal "this data should not change"
RGB_RED = (255, 0, 0)
# 4. Tuples are returned from functions as multiple values
def min_max(numbers):
return min(numbers), max(numbers) # returns a tuple
lo, hi = min_max([5, 2, 8, 1, 9]) # tuple unpacking
print(lo, hi) # 1 9from collections import namedtuple
# Create a named tuple "class"
Point = namedtuple("Point", ["x", "y"])
Person = namedtuple("Person", ["name", "age", "city"])
p = Point(3, 4)
print(p.x, p.y) # 3 4 — accessible by name!
print(p[0], p[1]) # 3 4 — still accessible by index
person = Person("Logesh", 22, "Chennai")
print(person.name) # Logesh
print(person) # Person(name='Logesh', age=22, city='Chennai')A set is an unordered, mutable collection of unique elements. Based on hash tables internally.
# Empty set — MUST use set(), not {} (that creates an empty dict)
empty = set()
# With elements
primes = {2, 3, 5, 7, 11}
mixed = {1, "hello", 3.14} # can mix types
# From a list — removes duplicates
nums = set([1, 2, 2, 3, 3, 3])
print(nums) # {1, 2, 3}
# Fast deduplication trick
dupes = [1, 2, 2, 3, 3, 4, 4]
unique = list(set(dupes))
print(unique) # [1, 2, 3, 4] (order not guaranteed)A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# Union — all elements from both sets
print(A | B) # {1, 2, 3, 4, 5, 6, 7, 8}
print(A.union(B)) # same
# Intersection — elements in BOTH sets
print(A & B) # {4, 5}
print(A.intersection(B))# same
# Difference — elements in A but NOT in B
print(A - B) # {1, 2, 3}
print(A.difference(B)) # same
# Symmetric Difference — elements in either A or B, but NOT both
print(A ^ B) # {1, 2, 3, 6, 7, 8}
print(A.symmetric_difference(B)) # same
# Subset and Superset
C = {1, 2}
print(C.issubset(A)) # True — all of C is in A
print(A.issuperset(C)) # True — A contains all of C
print(A.isdisjoint({6, 7})) # True — no common elementss = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.update([5, 6, 7]) # {1, 2, 3, 4, 5, 6, 7} — add multiple
s.remove(3) # KeyError if not found!
s.discard(99) # Safe — no error if not found
popped = s.pop() # Remove and return an arbitrary element
s.clear() # Empty the setfs = frozenset([1, 2, 3, 4])
# fs.add(5) # ❌ AttributeError — immutable
# Can be used as dictionary key (regular set cannot)
my_dict = {fs: "frozen set key"}A dictionary is an ordered (Python 3.7+), mutable collection of key-value pairs. Keys must be unique and hashable.
# Literal syntax
person = {
"name": "Logesh",
"age": 22,
"city": "Chennai"
}
# dict() constructor
person2 = dict(name="Logesh", age=22, city="Chennai")
# From list of tuples
pairs = [("a", 1), ("b", 2), ("c", 3)]
d = dict(pairs) # {'a': 1, 'b': 2, 'c': 3}
# Dict comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}data = {"name": "Python", "version": 3.12, "creator": "Guido"}
# Direct access — KeyError if key doesn't exist
print(data["name"]) # Python
# get() — safe access, returns None (or default) if key missing
print(data.get("version")) # 3.12
print(data.get("missing")) # None
print(data.get("missing", "N/A")) # N/A
# Check if key exists
print("name" in data) # True
print("salary" in data) # False
# All keys, values, items
print(data.keys()) # dict_keys(['name', 'version', 'creator'])
print(data.values()) # dict_values(['Python', 3.12, 'Guido'])
print(data.items()) # dict_items([('name', 'Python'), ...])d = {"a": 1, "b": 2}
# Add or update
d["c"] = 3 # {'a': 1, 'b': 2, 'c': 3}
d["a"] = 100 # Update existing: {'a': 100, 'b': 2, 'c': 3}
# update() — merge another dict
d.update({"d": 4, "e": 5})
d.update(f=6) # keyword args also work
# setdefault() — set ONLY if key doesn't exist
d.setdefault("a", 999) # 'a' already exists, no change
d.setdefault("z", 0) # 'z' is new, set to 0
# Remove
del d["b"] # remove key 'b'
val = d.pop("c") # remove 'c', returns its value
d.popitem() # remove and return the LAST inserted item
d.clear() # empty the dictd1 = {"a": 1, "b": 2}
d2 = {"b": 20, "c": 3}
# Merge with | operator
merged = d1 | d2 # {'a': 1, 'b': 20, 'c': 3} — d2 wins conflicts
print(merged)
# Update in-place
d1 |= d2
print(d1) # {'a': 1, 'b': 20, 'c': 3}from collections import defaultdict, Counter
# defaultdict — provides default value for missing keys
word_count = defaultdict(int)
text = "apple banana apple cherry banana apple"
for word in text.split():
word_count[word] += 1 # no KeyError, initializes to 0
print(dict(word_count)) # {'apple': 3, 'banana': 2, 'cherry': 1}
# Counter — even easier counting
c = Counter(text.split())
print(c) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(c.most_common(2)) # [('apple', 3), ('banana', 2)]data = [10, 20, 30, 40, 50]
# 0 1 2 3 4 (positive)
# -5 -4 -3 -2 -1 (negative)
print(data[0]) # 10 (first)
print(data[-1]) # 50 (last)
print(data[-2]) # 40 (second to last)s = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [start:stop] — from start (inclusive) to stop (exclusive)
print(s[2:5]) # [2, 3, 4]
# [:stop] — from beginning
print(s[:4]) # [0, 1, 2, 3]
# [start:] — to end
print(s[6:]) # [6, 7, 8, 9]
# [::step] — every nth element
print(s[::2]) # [0, 2, 4, 6, 8] (every 2nd)
print(s[::3]) # [0, 3, 6, 9]
# Reverse using slice
print(s[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# [start:stop:step] — full control
print(s[1:8:2]) # [1, 3, 5, 7]
# Slicing creates a COPY (for lists)
copy = s[:] # Full copy of the list
# Strings work the same way
text = "Hello, World!"
print(text[7:12]) # World
print(text[::-1]) # !dlroW ,olleHList comprehension is a concise, Pythonic way to create lists. They are also faster than traditional for loops.
[expression for item in iterable if condition]
# Traditional loop
squares = []
for x in range(1, 6):
squares.append(x ** 2)
# List comprehension → same result, one line
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With condition (filter)
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# String transformations
words = ["hello", "world", "python"]
upper = [w.upper() for w in words]
print(upper) # ['HELLO', 'WORLD', 'PYTHON']
# Filter strings by condition
long_words = [w for w in words if len(w) > 4]
print(long_words) # ['hello', 'world', 'python']# Nested comprehension — flatten 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Conditional expression in comprehension (ternary)
nums = [1, 2, 3, 4, 5, 6]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd', 'even']
# Dict comprehension
names = ["Alice", "Bob", "Charlie"]
name_lengths = {name: len(name) for name in names}
print(name_lengths) # {'Alice': 5, 'Bob': 3, 'Charlie': 7}
# Set comprehension
unique_lengths = {len(name) for name in names}
print(unique_lengths) # {3, 5, 7}
# Generator expression (lazy — doesn't create list in memory)
gen = (x ** 2 for x in range(1_000_000)) # No memory overhead!
print(next(gen)) # 0
print(next(gen)) # 1
# Useful for large datasets
total = sum(x ** 2 for x in range(1_000_000)) # Memory efficient!# Nested list (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # 6 (row 1, column 2)
# Nested dict (JSON-like data)
user = {
"id": 1,
"name": "Logesh",
"address": {
"city": "Chennai",
"state": "Tamil Nadu",
"zip": "600001"
},
"skills": ["Python", "JavaScript", "React"]
}
print(user["address"]["city"]) # Chennai
print(user["skills"][0]) # Python
# Modifying nested structure
user["address"]["zip"] = "600002"
user["skills"].append("Node.js")
# List of dicts (very common in real apps — like database records)
students = [
{"name": "Alice", "grade": 90},
{"name": "Bob", "grade": 85},
{"name": "Charlie", "grade": 92},
]
# Sort by grade descending
students.sort(key=lambda s: s["grade"], reverse=True)
print(students[0]) # {'name': 'Charlie', 'grade': 92}
# Get all names
names = [s["name"] for s in students]
print(names) # ['Charlie', 'Alice', 'Bob']
# Filter
high_achievers = [s for s in students if s["grade"] >= 90]This is a critical concept when working with nested/mutable data.
Original ──► Outer Object
│
Inner Object(s)
Shallow Copy ──► NEW Outer Object
│
SAME Inner Object(s) ← shared reference!
Deep Copy ──► NEW Outer Object
│
NEW Inner Object(s) ← completely independent!
import copy
original = [1, [2, 3], [4, 5]]
# Methods that create shallow copies:
shallow1 = original[:] # slice
shallow2 = original.copy() # .copy() method
shallow3 = list(original) # list() constructor
shallow4 = copy.copy(original) # copy.copy()
# Outer list is different
print(original is shallow1) # False — different outer list
# BUT inner lists are the SAME objects!
print(original[1] is shallow1[1]) # True — shared!
# Proof: modifying inner list affects BOTH
shallow1[1].append(99)
print(original) # [1, [2, 3, 99], [4, 5]] — original changed!
print(shallow1) # [1, [2, 3, 99], [4, 5]]
# But changing the outer list doesn't affect original
shallow1.append("new")
print(original) # [1, [2, 3, 99], [4, 5]] — original unchangedimport copy
original = [1, [2, 3], [4, 5]]
deep = copy.deepcopy(original)
# Everything is completely independent
deep[1].append(99)
print(original) # [1, [2, 3], [4, 5]] — untouched!
print(deep) # [1, [2, 3, 99], [4, 5]]
# Deep copy with nested dicts
config = {
"database": {"host": "localhost", "port": 5432},
"cache": {"host": "redis", "port": 6379}
}
config_copy = copy.deepcopy(config)
config_copy["database"]["host"] = "production.server.com"
print(config["database"]["host"]) # localhost — safe!
print(config_copy["database"]["host"]) # production.server.com| Situation | Use |
|---|---|
| Flat structure (no nested objects) | Shallow copy is safe |
| Nested mutable objects, need independence | Deep copy |
| Sharing data intentionally | Assignment (b = a) |
| Large nested structure (performance concern) | Consider manual copy |
# Packing — combine multiple values into one container
coordinates = 10, 20, 30 # packed into a tuple (parentheses optional)
print(coordinates) # (10, 20, 30)
print(type(coordinates)) # <class 'tuple'># Unpacking — pull values out of a container
x, y, z = (10, 20, 30)
print(x, y, z) # 10 20 30
# Works with any iterable
a, b, c = [1, 2, 3]
first, second, third = "abc"
print(first, second, third) # a b c
# Swap (uses packing and unpacking simultaneously)
a, b = 5, 10
a, b = b, a # Pythonic swap
print(a, b) # 10 5# * catches "the rest" as a list
first, *rest = [1, 2, 3, 4, 5]
print(first) # 1
print(rest) # [2, 3, 4, 5]
*beginning, last = [1, 2, 3, 4, 5]
print(beginning) # [1, 2, 3, 4]
print(last) # 5
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
# Ignore values with _
_, important, _ = (10, 42, 99)
print(important) # 42def add(a, b, c):
return a + b + c
args = [1, 2, 3]
print(add(*args)) # 6 — unpack list as positional args
kwargs = {"a": 1, "b": 2, "c": 3}
print(add(**kwargs)) # 6 — unpack dict as keyword args
# Combine list and other values
nums = [2, 3]
print(add(1, *nums)) # 6
# Unpack into another list
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = [*list1, *list2]
print(combined) # [1, 2, 3, 4, 5, 6]
# Merge dicts using **
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
merged = {**d1, **d2}
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}from collections import deque, OrderedDict, ChainMap, defaultdict, Counter
# ─── deque — Double-Ended Queue ───────────────────────────────────────────
# O(1) append and pop from BOTH ends (list is O(n) for left side!)
dq = deque([1, 2, 3])
dq.append(4) # [1, 2, 3, 4]
dq.appendleft(0) # [0, 1, 2, 3, 4]
dq.pop() # removes 4
dq.popleft() # removes 0 — O(1)! list.pop(0) is O(n)
# Rotate — shift elements right (+) or left (-)
dq = deque([1, 2, 3, 4, 5])
dq.rotate(2) # [4, 5, 1, 2, 3] (right by 2)
dq.rotate(-1) # [5, 1, 2, 3, 4] (left by 1)
# maxlen — fixed-size sliding window
recent = deque(maxlen=3)
for item in [1, 2, 3, 4, 5]:
recent.append(item)
print(recent) # deque([3, 4, 5], maxlen=3)
# Use deque when you need:
# - Queue (FIFO): appendleft + pop, or append + popleft
# - Stack (LIFO): append + pop (same as list)
# - Sliding window of fixed size# ─── heapq — Priority Queue (Min-Heap) ───────────────────────────────────
import heapq
nums = [5, 3, 8, 1, 9, 2]
heapq.heapify(nums) # Convert list to heap in-place: O(n)
print(nums[0]) # 1 — always the SMALLEST element
heapq.heappush(nums, 0) # Add 0, maintain heap property
print(heapq.heappop(nums)) # 0 — removes and returns smallest
# Get N smallest/largest
data = [5, 3, 8, 1, 9, 2]
print(heapq.nsmallest(3, data)) # [1, 2, 3]
print(heapq.nlargest(3, data)) # [9, 8, 5]
# Max-heap trick: negate the values
max_heap = []
for n in [5, 3, 8, 1, 9]:
heapq.heappush(max_heap, -n) # Store negative values
max_val = -heapq.heappop(max_heap) # Negate back: 9
# Priority queue with tuples (heap sorts by first element)
tasks = []
heapq.heappush(tasks, (3, "low priority"))
heapq.heappush(tasks, (1, "urgent"))
heapq.heappush(tasks, (2, "medium"))
while tasks:
priority, task = heapq.heappop(tasks)
print(f"[{priority}] {task}")
# [1] urgent
# [2] medium
# [3] low priority# ─── OrderedDict ─────────────────────────────────────────────────────────
# In Python 3.7+, regular dict preserves insertion order too.
# OrderedDict has extra features:
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3
# Move to end / beginning
od.move_to_end("a") # Move 'a' to end
od.move_to_end("c", last=False) # Move 'c' to beginning
# Compare order matters for OrderedDict
od1 = OrderedDict([("a", 1), ("b", 2)])
od2 = OrderedDict([("b", 2), ("a", 1)])
print(od1 == od2) # False (different order!)
d1 = {"a": 1, "b": 2}
d2 = {"b": 2, "a": 1}
print(d1 == d2) # True (regular dict — order doesn't matter for ==)# ─── ChainMap — Layered Lookup ────────────────────────────────────────────
# Combines multiple dicts into a single view (lookups check each in order)
defaults = {"color": "blue", "size": "medium", "font": "Arial"}
user_settings = {"color": "red"}
system_settings = {"size": "large"}
config = ChainMap(user_settings, system_settings, defaults)
print(config["color"]) # "red" ← from user_settings (first)
print(config["size"]) # "large" ← from system_settings
print(config["font"]) # "Arial" ← from defaults (last)
# Real use case: layered configuration (user > env > defaults)
import os
env_config = {"DEBUG": os.getenv("DEBUG", "False")}
file_config = {"DEBUG": "True", "PORT": "8080"}
app_config = ChainMap(env_config, file_config)| Operation | list | tuple | set | dict |
|---|---|---|---|---|
| Access by index | O(1) | O(1) | N/A | N/A |
| Access by key | N/A | N/A | N/A | O(1) avg |
Search (x in) |
O(n) | O(n) | O(1) avg | O(1) avg |
| Insert at end | O(1) amort | N/A | O(1) avg | O(1) avg |
| Insert at start | O(n) | N/A | O(1) avg | O(1) avg |
| Delete by index | O(n) | N/A | N/A | N/A |
| Delete by value | O(n) | N/A | O(1) avg | O(1) avg |
| Sort | O(n log n) | N/A | N/A | N/A |
Length (len) |
O(1) | O(1) | O(1) | O(1) |
🔑 Use
setordictfor fast lookups. Usedequewhen you need fast operations at both ends.
Q1: What's the difference between a list and a tuple?
List: Ordered, mutable (changeable), uses
[]. Use for collections that may change. Tuple: Ordered, immutable (fixed), uses(). Use for fixed data; faster than lists; can be used as dict keys.
Q2: When would you use a set over a list?
When you need: (1) uniqueness — sets automatically remove duplicates; (2) O(1) membership testing —
x in setis O(1), whilex in listis O(n); (3) mathematical set operations — union, intersection, difference.
Q3: Can you have a list as a dict key?
No. Dict keys must be hashable (immutable). Lists are mutable and not hashable. Use a tuple instead.
d = {[1,2]: "bad"} # ❌ TypeError: unhashable type: 'list'
d = {(1,2): "good"} # ✅Q4: What's the difference between append() and extend()?
lst = [1, 2, 3]
lst.append([4, 5]) # [1, 2, 3, [4, 5]] — adds as SINGLE element
lst.extend([6, 7]) # [1, 2, 3, [4, 5], 6, 7] — adds each elementQ5: What is a shallow copy and when does it fail?
A shallow copy creates a new outer container but keeps references to the same inner objects. It "fails" (gives unexpected behavior) when the original contains mutable nested objects (e.g., lists within lists). Modifying a nested object in the copy also modifies the original. Use
copy.deepcopy()to avoid this.
Q6: How do you count occurrences of items efficiently?
from collections import Counter
items = ["apple", "banana", "apple", "cherry", "apple"]
count = Counter(items)
print(count["apple"]) # 3
print(count.most_common(2)) # [('apple', 3), ('banana', 1)]Q7: How does negative indexing work?
data[-1]is equivalent todata[len(data) - 1]. Python adds the negative index to the length to get the actual index.-1→ last element,-2→ second-to-last, etc.
Q8: What is list comprehension and why is it better than a loop?
List comprehension is a syntactic construct to create lists in a single line. It is: (1) more readable for simple transformations; (2) faster — implemented in C internally, can be 35–50% faster than equivalent for loops; (3) Pythonic. However, for complex multi-step logic, a regular loop may be clearer.
Q9: What is a deque and when do you use it?
collections.dequeis a double-ended queue with O(1) appends and pops from both ends. Use it when you need: a FIFO queue, a fixed-size sliding window (maxlen), or when you frequentlypop(0)from a list (which is O(n) — deque'spopleft()is O(1)).
Q10: What is a heap and how does heapq work?
A heap is a tree-based data structure where the parent is always smaller than children (min-heap). Python's
heapqimplements a min-heap using a regular list.heappush()andheappop()are O(log n). Use it for priority queues and "find N smallest/largest" efficiently.
Next: 04 — Input & Output →