[Tutor] removing items from list in for loop
Cameron Simpson
cs at cskk.id.au
Sun Feb 13 16:54:03 EST 2022
On 13Feb2022 08:52, marcus.luetolf at bluewin.ch <marcus.luetolf at bluewin.ch> wrote:
>create from a list of n items, n copies of this list in a for loop with
>one item successivly removed at each iteration.
>
>I should get n copies each with n-1 items.
>
>
>Beeing aware of problems arising when a list is alterated during an
>iteration I tried to get around using a copy oft he original list.
[...]
You code here:
all_items = ['item1 ','item2 ', ......]
copy_all_items = ... the same list definition ...
for item in copy_all_items:
copy_all_items.remove(item)
copy_all_items = all_items
print(item, copy_all_items)
does not do what you think. Specificly this step:
copy_all_items = all_items
Does not make a copy of "all_items". Instead, it makes "copy_all_items"
a reference to the original list referenced by "all_items". From then on
you're modifying the "all_items" list. So your first pass for "item1 "
removed from your original duplicate list, because that is what
"copy_all_items" referred to. Every subsequent pass removed from the
first list.
Only the fact that your for-loop iterates over the original
"copy_all_items" brings even a semblance of normal operation.
The quick way to copy a list is either:
list2 = list(list1)
which constructs a new list from the elements in "list1" or:
list2 = list1[:]
which constructs a new list as a slice of from "list1", but the slice is
the size of the entire list, thus a copy.
Both of these construct new lists. Compared with:
list2 = list1
which just makes "list2" point at the same list as "list1". No second
list is made/copied.
Note that _all_ Python variables are references, and an assigment
statement never copies the contents of an object - it just takes an
object reference (the right hand side) and places it in the variable on
the left hand side.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list