Max Beikirch
Max Beikirch

Reputation: 2133

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.

Upvotes: 1

Views: 83

Answers (3)

Avinash
Avinash

Reputation: 875

Try this:

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

l = [a,b]

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

If you've more than one occurrence of 2, you can try:

for i in l:
    try:
        while True:
            i.remove(2)
    except ValueError:
        pass
  

Output:

[1]
[3]
[[1], [3]]

Upvotes: 1

Chris
Chris

Reputation: 36486

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.

Upvotes: 1

blhsing
blhsing

Reputation: 106445

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

Upvotes: 2

Related Questions