Removing items from unnamed lists in Python

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 above construction to avoid explicitly specifying a list for the sole purpose of passing it to a function, that is:

 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?

+4
source share
2 answers

In python, inline methods that work in place return None to make it absolutely transparent that they mutated the object.

Of course, you can ignore this convention and write your own wrapper:

 def my_remove(lst,what): lst.remove(what) return lst 

But I would not recommend it.

As a side note, if you want to do something like:

 list(something_convertible_to_list).remove('item') 

but return the list, the following may be useful enough to be useful:

 [x for x in something_iterable if x != 'item'] 

And this returns the list, but where list.remove removes only 1 'item' , this will lead to the creation of a new list without the 'item' in it.

+9
source

You can try something like:

 my_list[:my_list.index('item')]+my_list[my_list.index('item')+1:] 

although you have two requests.

or

 [item for item in my_sequence if item != 'item'] 

The first one will remove the first 'item' from the list, and the second one will delete all the 'item' .

+1
source

All Articles