Search code examples
pythonlist-comprehension

Filter lists that are stored in a list


I have a few lists that I want filtered. Consider the following example:

a = [1,2]
b = [2,3]

l = [a,b]

for i in l:
  i = [elem for elem in l if elem != 2]

I want the output to be a==[1], b==[3], but it looks like the update of i does not change the elements a or b. In C++, I'd use a pointer but I can't seem to find the corresponding concept in Python.


Solution

  • By assigning to i a new list in your for loop, it loses its reference to a and b so they do not get updated. Instead, you should update i in-place. You should also iterate through i instead of l to filter each sub-list:

    for i in l:
        i[:] = (elem for elem in i if elem != 2)
    

    Demo: https://replit.com/@blhsing/BlissfulWhichGravity