Why doesn't the following statement return a list without 'item' in Python?
list(something_convertible_to_list).remove('item')
?
I would like to use the construction above to avoid explicitly naming a list for the sole purpose of passing it to a function, i.e.:
operate_on_list(list(something_convertible_to_list).remove('item'))
def operate_on_list(my_list):
# do_something
print my_list
return
Is this possible in Python?
In python, built-in methods which operate in place return None to make it absolutely clear that they mutated an object.
Of course, you're free to disregard this convention and write your own wrapper:
def my_remove(lst,what):
lst.remove(what)
return lst
But I wouldn't recommend it.
As a side note, if you want to do something like:
list(something_convertible_to_list).remove('item')
but get the list back, the following might be similar enough to be useful:
[x for x in something_iterable if x != 'item']
And this does return a list, but where list.remove only takes away 1 'item', this will construct a new list with no 'item' in it.
You can try something like:
my_list[:my_list.index('item')]+my_list[my_list.index('item')+1:]
although you do have two searches here.
or
[item for item in my_sequence if item != 'item']
The first one will remove the first 'item' from the list, while the second one will remove every 'item'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With