8

I want to remove item from a list called mom. I have another list called cut

mom= [[0,8,1], [0, 6, 2, 7], [0, 11, 12, 3, 9], [0, 5, 4, 10]]
cut =[0, 9, 8, 2]

How do I remove what in cut from mom, except for zero?

My desire result is

mom=[[0,1],[0,6,7],[0,11,12,3],[0,5,4,10]]
user02
  • 281
  • 3
  • 10

4 Answers4

9
>>> [[e for e in l if e not in cut or e == 0] for l in mom]
[[0, 1], [0, 6, 7], [0, 11, 12, 3], [0, 5, 4, 10]]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

This is how I'd do it with List comprehension.

mom= [[0,8,1], [0, 6, 2, 7], [0, 11, 12, 3, 9], [0, 5, 4, 10]]
cut =[0, 9, 8, 2]
mom = [[x for x in subList if x not in cut or x == 0 ] for subList in mom ]
Dom DaFonte
  • 1,619
  • 14
  • 31
0

The answers provided by Ingnacio and Dom are perfect. The same can be done in a more clear and easy to understand way. Try the following:

mom= [[0,8,1], [0, 6, 2, 7], [0, 11, 12, 3, 9], [0, 5, 4, 10]]

cut =[0, 9, 8, 2]

for e in mom:



for f in e:


if f in cut and f != 0:


e.remove(f)  #used the remove() function of list

print(mom)

Much easier for a novice in Python. Isn't it?

Sandip Nath
  • 622
  • 2
  • 8
  • 18
0

Given the cut=[0,9,8,2] and mom = [[0,8,1], [0, 6, 2, 7], [0, 11, 12, 3, 9], [0, 5, 4, 10]]

Assuming 0 element is removed from cut list

cut=[9,8,2]

result =[] for e in mom: result.append(list(set(e)-set(cut)))

o/p result

[[0, 1], [0, 6, 7], [0, 11, 3, 12], [0, 10, 4, 5]]

Manjunath
  • 123
  • 1
  • 1
  • 4