fruits = ['apple', 'banana', 'cherry']
✅ Ordered
✅ Mutable
✅ Duplicates allowed
✅ Index-based access
✅ Can contain any type (even mixed)
ADVANCED CONCEPTS
- List Comprehensions with Conditionals You already know:
squares = [x*x for x in range(10)]
But let’s evolve:
even_squares = [x*x for x in range(20) if x % 2 == 0]
How about nested ifs?
result = [x for x in range(100) if x % 2 == 0 if x % 5 == 0]
🔍 Use Case:
Filtering database IDs that are both even and multiples of 5.
- Nested List Comprehensions Think of a 2D matrix (row x column):
matrix = [[i * j for j in range(3)] for i in range(3)]
## [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Flatten it like a pancake:
flat = [item for row in matrix for item in row]
🔍 Use Case:
Flattens API response JSON or CSV table data into a single list.
- Advanced Slicing Techniques
data = list(range(10)) # [0, 1, 2, ..., 9]
print(data[::-1]) # Reverse: [9, 8, ..., 0]
print(data[::2]) # Every second: [0, 2, 4, 6, 8]
print(data[1:8:3]) # Slice with step: [1, 4, 7]
🔍 Use Case:
Time-series data sampling, custom pagination.
- Unpacking With * Operator
a, *middle, b = [1, 2, 3, 4, 5]
## a=1, b=5, middle=[2,3,4]
🔍 Use Case:
Grab first/last log lines, and chunk the rest for processing.
- List as a Queue vs. Stack ## Stack
stack = []
stack.append(1)
stack.pop()
## Queue (inefficient)
queue = [1, 2, 3]
queue.pop(0) # Slow!
Use deque instead for performance
from collections import deque
q = deque([1,2,3])
q.popleft() # Efficient O(1)
🔍 Use Case:
Building job schedulers, undo/redo stacks.
- Mutability Pitfalls
a = [[0]*3]*3
a[0][0] = 99
Changes ALL rows!
Why? Because inner lists are references to the same object.
Fix it:
a = [[0]*3 for _ in range(3)]
🔍 Use Case:
Avoid accidental data corruption in nested data (e.g. spreadsheets, grids).
- Using enumerate() and zip() Cleanly
words = ['alpha', 'beta', 'gamma']
for idx, word in enumerate(words, start=1):
print(f"{idx}: {word}")
Combine lists:
ids = [1, 2, 3]
names = ['nova', 'tesla', 'ida']
for id, name in zip(ids, names):
print(f"{id}: {name}”)
🔍 Use Case:
Log display with IDs, user dashboards, matched input-output display.
- List vs. Generator Performance
big = [x for x in range(10**6)] # List in memory
lazy = (x for x in range(10**6)) # Generator, lazy eval
✅ Use lists when you need random access
✅ Use generators when memory is tight
🔍 Use Case:
Backend logs, telemetry pipelines, stream processing.
Want more? I write Python how-tos at [Novaxis] — no fluff, just clean backend logic.
Subscribe for free novaxis.substack.com
Nova of Novaxis | Substack
novaxis.substack.com
Top comments (0)