Home > Net >  Filter lists that are stored in a list
Filter lists that are stored in a list

Time:05-12

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.

CodePudding user response:

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

CodePudding user response:

Are you certain you don't just want something like the following?

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

l = [[i for i in a if i != 2], [i for i in b if i != 2]]

Or perhaps more flexibly:

exclude = (2,)

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

l = [a, b]
l = [[i for i in x if not any(i == e for e in exclude)] for x in l]

This latter approach makes it each to add additional sublists to l, and to specify more numbers to exclude from them.

CodePudding user response:

Try this:

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

l = [a,b]

for i in l:
    i.remove(2)
  
print(a)
print(b)
print(l)

Output:

[1]
[3]
[[1], [3]]
  • Related