[Tutor] removing items from list in for loop
Peter Otten
__peter__ at web.de
Sun Feb 13 05:56:01 EST 2022
On 13/02/2022 08:52, marcus.luetolf at bluewin.ch wrote:
> Hello Experts, I am still trying to
>
> create from a list of n items, n copies of this list in a for loop with one
> item successivly removed at each iteration.
>>> def build_lists(items):
result = []
for value in items:
# copy the original list
copy = items[:]
# remove the current value from the copy
copy.remove(value)
# append to the result (a list of lists)
result.append(copy)
return result
>>> build_lists(["Peter", "Paul", "Mary"])
[['Paul', 'Mary'], ['Peter', 'Mary'], ['Peter', 'Paul']]
But note a potential problem with this:
>>> build_lists([1, 2, 1.0])
[[2, 1.0], [1, 1.0], [2, 1.0]]
You always remove the first match. If you have duplicates and want to
remove the right occurrence you need to delete rather than remove. One way:
>>> def deleted(items, index):
result = items[:]
del result[index]
return result
>>> items = [1, 2, 1.0]
>>> [deleted(items, i) for i in range(len(items))]
[[2, 1.0], [1, 1.0], [1, 2]]
More information about the Tutor
mailing list