[Tutor] removing items from list in for loop
Dennis Lee Bieber
wlfraed at ix.netcom.com
Sun Feb 13 13:45:47 EST 2022
On Sun, 13 Feb 2022 08:52:14 +0100, <marcus.luetolf at bluewin.ch> declaimed
the following:
>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.
It would help if you showed us, for a toy data set, the input list, AND
all appropriate output lists.
Secondly, do you need to accumulate the lists (eg: a list of output
lists) for later usage, or do you just need to dump each to the display?
The first time you posted this matter, I jumped into the deep end using
a module with a function to generate combinations (not permutations) --
since what you seem to be asking for is
all combinations of N items taken N-1 at a time
That is almost a one-liner; the code to display each combination takes up
more space then generating them.
>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.
>
>However I got strange results, the copied list getting shorter at each
>iteration or the items didn't got removed in order.
>
Try to rethink the problem... As you have it, you are trying 1) extract
one item from some list, 2) asking Python to remove that same item from a
copy of the same list (which means Python has to loop over the list trying
to match the item), 3) and repeat for each item in the original list.
That's a lot of (hidden) looping/matching being performed.
Assuming I understand the assignment -- you don't even need to start
with a copy of the list and remove one item from it... Just slice the
original list /skipping/ one item to create the result list. That just
requires knowing the position in the list to be excluded.
>>> alist = list(range(10))
>>> alist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> rlist = alist[:2] + alist[3:]
>>> rlist
[0, 1, 3, 4, 5, 6, 7, 8, 9]
>>> rlist = alist[:0] + alist[1:]
>>> rlist
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> rlist = alist[:9] + alist[10:]
>>> rlist
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>>
It should be trivial to create a loop that starts with the first
position and goes to the length of the list.
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
More information about the Tutor
mailing list