Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing items from unnamed lists in Python

Tags:

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 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?

like image 552
Amelio Vazquez-Reina Avatar asked Dec 26 '22 09:12

Amelio Vazquez-Reina


2 Answers

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.

like image 189
mgilson Avatar answered Dec 28 '22 23:12

mgilson


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'.

like image 35
dmg Avatar answered Dec 28 '22 23:12

dmg