-2

I was trying to remove an element from multiple lists within a list using .remove() method, which I know works for lists. I also used list comprehension. As an example, consider:

abc = [["a","b"],["a","c"]]
bc = [apple.remove("a") for apple in abc]
print(bc)

It will return the output [None, None]. I am curious why does happen and also what is the method I can use to achieve my desired output of [["b"], ["c"]].

2 Answers2

1

You get the output [None, None] because list.remove() operates in-place and modifies the original list. You have two options:

  1. Just operate on the original list. Note that it is not a good practice to use a list-comprehension for its side-effects (see here), so we should just write a regular loop here:
>>> for apple in abc:
...    apple.remove("a")

Then, you can abc to see that you have the desired result:

>>> print(abc)
[['b'], ['c']]

  1. Create a copy of the original lists, excluding the items to be removed:
>>> bc = [[item for item in apple if item != "a"] for apple in abc]

which gives you the desired output in bc, but leaves the original list unchanged:

>>> print(abc)
[['a', 'b'], ['a', 'c']]
>>> print(bc) 
[['b'], ['c']]
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
0

Remove is an in-place operation

you are changing the original abc data structure. to see the changes you should print(abc)

Glauco
  • 1,385
  • 2
  • 10
  • 20