Lists — Advanced Patterns
Shallow copy traps, modify-while-iterating bugs, sort vs sorted, and lists as stacks/queues
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
You know what a list is. This atom is about the bugs that bite experienced developers.
The modify-while-iterating trap:
python nums = [1, 2, 3, 4, 5] for n in nums: if n % 2 == 0: nums.remove(n) # SILENT BUG — skips elements print(nums) # [1, 3, 5] — looks right, but... nums = [2, 4, 6, 8] for n in nums: if n % 2 == 0: nums.remove(n) print(nums) # [4, 8] — WRONG! 4 and 8 are skipped Fix: iterate over a copy: for n in nums[:]` or use a list comprehension.
Shallow copy vs deep copy:
python a = [1, [2, 3], 4] b = a[:] # shallow copy — b is a new list... b[0] = 99 # ...but inner lists are still shared b[1][0] = 99 # THIS MODIFIES a[1][0] TOO print(a) # [1, [99, 3], 4] ← a was changed! Fix: import copy; b = copy.deepcopy(a)`
sort() vs sorted():
python nums = [3, 1, 4, 1, 5] sorted_nums = sorted(nums) # returns NEW list, nums unchanged nums.sort() # modifies IN PLACE, returns None result = nums.sort() # result is None — common mistake
List as stack (LIFO): append() + pop() — O(1) both ends. List as queue (FIFO): Use collections.deque — list.pop(0) is O(n).
Examples
Safe iteration — iterate over a copy
Always filter via comprehension or iterate a copy
nums = [1, 2, 3, 4, 5, 6]
# Wrong — modifying while iterating
# for n in nums:
# if n % 2 == 0: nums.remove(n)
# Right — comprehension (clearest)
nums = [n for n in nums if n % 2 != 0]
print(nums) # [1, 3, 5]
# Also right — copy slice
for n in nums[:]:
if n > 3: nums.remove(n)How well did you understand this?
Next in Python Core
Dicts — Advanced Patterns