📋 Lists & Tuples, lesson 4 of 6
Copies, aliases and safe loops
Understand why changing one list can change 'another', and how to copy.
10 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
A variable doesn't contain a list; it points to
one. So b = a does not copy anything. It gives
the same list a second name (an alias). Change it
through either name and both "see" the change.
Two names, one list
is checks whether two names point to the very same object.
To get an independent copy, use any of these:
items.copy()list(items)items[:](a slice of everything)
== compares contents; is compares
identity (same object).
A real copy
Replace .copy() with [:]. Same result!
What does this print?
The skipping bug
We wanted only odd numbers left, but one 2 and one 4 slipped through.
The fix: build a new list
Another fix: loop over a copy with for n in nums[:]: and remove from nums.
What does this print?
Filter the inbox
Build a new list clean with every message from
inbox except "SPAM", in the same order.
Leave inbox unchanged.