1

I have following list of lists object

myList = [[123,0.0,345,0.0,0.0,0.0],
 [45,0.0,0.0,0.0],
 [67,8,0.0,5,6,7,0.0]

And I want to remove all zeroes from this list.

I followed this question and coded like following.

myList = list(filter(lambda j:j!=0,myList[i]) for i in range(len(myList)))

But I am getting the list of filter object as the output. What is the error in the code.

[<filter object at 0x7fe7bdfff8d0>, <filter object at 0x7fe7a6eaaf98>, <filter object at 0x7fe7a6f08048>,
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
Malintha
  • 4,512
  • 9
  • 48
  • 82

4 Answers4

7

You forgot to cast the inner filter function with a list, when you do that, the code works as expected :)

myList = [[123,0.0,345,0.0,0.0,0.0],
 [45,0.0,0.0,0.0],
 [67,8,0.0,5,6,7,0.0]]

#Cast inner filter into a list
myList = list(list(filter(lambda j:j!=0,myList[i])) for i in range(len(myList)))
print(myList)

The output will be

[[123, 345], [45], [67, 8, 5, 6, 7]]

Also a simpler way of understanding will be to use a list-comprehension

myList = [[123,0.0,345,0.0,0.0,0.0],
 [45,0.0,0.0,0.0],
 [67,8,0.0,5,6,7,0.0]]

#Using list comprehension, in the inner loop check if item is non-zero
myList = [ [item for item in li if item != 0] for li in myList ]
print(myList)

The output will be

[[123, 345], [45], [67, 8, 5, 6, 7]]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

Try this :

newList = [list(filter(lambda j:j!=0, i)) for i in myList]

OUTPUT :

[[123, 345], [45], [67, 8, 5, 6, 7]]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
0

You could also do this with a list comprehension:

cleaned = [ [e for e in row if e != 0] for row in myList ]
Alain T.
  • 40,517
  • 4
  • 31
  • 51
-1

You just need to wrap filter, not the whole statement:

myList = [list(filter(lambda j:j!=0,myList[i]) for i in range(len(myList))]

Also, you can skip the index, and iterate by lists in myList:

myList = [list(filter(lambda j:j!=0, inner_list) for inner_list in myList]
Relandom
  • 1,029
  • 2
  • 9
  • 16