[Python-ideas] Allow multiple arguments to `list.remove` and flag for silent fail
Steven D'Aprano
steve at pearwood.info
Tue Aug 27 03:47:11 CEST 2013
On 27/08/13 03:11, Ram Rachum wrote:
> Why do I have to do this:
>
> for thing in things:
> try:
> my_list.remove(thing)
> except ValueError:
> pass
>
>
> When I could do this:
>
> my_list.remove(*things, silent_fail=True)
How is the remove method supposed to distinguish between existing code that does this:
my_list.remove((1, 2, 3)) # remove a single item, a tuple (1, 2, 3)
and new code that does this?
my_list.remove(1, 2, 3) # remove three items, 1, 2 and 3, without suppressing errors
Justify why remove(a, b, c) should mean "remove the first of each of a and b and c" rather than "remove the first of a, or if no a, the first b, or if no b, the first c", that is, this code instead:
try:
for thing in things:
my_list.remove(thing)
except ValueError:
pass
Both are useful. Why is your example more useful than mine?
But even more useful than both would be, "remove the first occurring of either a, b or c":
indexes = []
for thing in things:
try:
indexes.append(my_list.index(thing)
except ValueError:
pass
del my_list[min(indexes)]
So that's three distinct behaviours that remove(a, b, c, ...) could mean. All of them are easy enough to program, and none of them are fundamental list operations. Justify why one of them should be privileged as a method.
> Aside from being much more concise, it could be more efficient too,
> couldn't it?
If you're worried about efficiency or removals, a list is probably the wrong data structure to use.
--
Steven
More information about the Python-ideas
mailing list