Neekoy Neekoy - 1 month ago 13
Python Question

Python list comprehension and do action

Is it possible to do an action with the item in a list comprehension?

Example:

list = [1, 2, 3]
list_filtered = [ i for i in list if i == 3 AND DO SOMETHING WITH I]
print (list_filtered)


For example if I want to remove the '3' how would I go about it? Logic says that it's something like:

list = [1, 2, 3]
list_filtered = [ i for i in list if i == 3 && list.remove(i) ]
print (list_filtered)


I can't seem to make Python perform an action with that 'i' with any syntax that I tried. Can someone please elaborate?

EDIT: Sorry, the explanation might not be clear enough. I know how to iterate and create the new list. I want to create "list_filtered" and remove that value from "list" if it fits the "IF" statement.

Practically I need the following:

list = [1, 2, 3]
list_filtered = [ i for i in list if i == 3 && list.remove(i) ]
print (list_filtered)
# output >> [3]
print (list)
# output >> [1, 2]


I hope the above makes it more clear. Also, please note that my question is if this can be done in the list comprehension specifically. I know how to do it with additional code. :)

EDIT2: Apparently what I wanted to do isn't possible and also isn't advisable (which is the reason it isn't possible). It seemed like a logical thing that I just didn't know how to do. Thanks guys :)

Answer

Your miss understand the purpose of list comprehension. List comprehension should be used to create a list, not to use its side effects. Further more, as Prune has already mentioned, you should never modify a container while iterating over it.

If you want to filter out certain elements in a list using list comprehension, use an if statement:

>>> l = [1, 2, 3]
>>> l_filtered = [i for i in l if i != 3]
>>> l_filtered
[1, 2]
>>> 

Alternatively, you can use the builtin function filter():

>>> l = [1, 2, 3]
>>> l_filtered = list(filter(lambda x: x != 3, l))
>>> l_filtered
[1, 2]
>>>

Edit: Based on your most recent edit, what your asking is absolutely possible. Just use two different list comprehensions:

>>> l = [1, 2, 3]
>>> l_filtered = [i for i in l if i == 3]
>>> l_filtered
[3]
>>> l = [i for i in l if i != 3] # reassigning the value of l to a new list
>>> l
[1, 2]
>>>
Comments