0

The code I currently have:

lst = [[0, 0, 0, 0, 0, 1], [1, 2, 3, 4, 5, 4, 3, 0], [1, 4, 5, 6, 7, 0]]

for week in lst:
    print(week)
    for day in week:
        if day == 0:
            week.remove(day)

print(lst)
#[[0, 0, 1], [1, 2, 3, 4, 5, 4, 3], [1, 4, 5, 6, 7]]

I have hard time understanding why the zeroes in the first sublist are not being removed

4 Answers4

0

Is this what you're looking for?

lst = [[0, 0, 0, 0, 0, 1], [1, 2, 3, 4, 5, 4, 3, 0], [1, 4, 5, 6, 7, 0]]

lst = [[j for j in x if not j == 0] for x in lst]
lst

output

[[1], [1, 2, 3, 4, 5, 4, 3], [1, 4, 5, 6, 7]]
Kavi Harjani
  • 661
  • 5
  • 15
0

The problem with your code is that you edit the list while working with it. For this reason every second zero in the first sublist is not even being checked, let alone removed. Little improvement on your code saves indexes of zeroes and then deletes them.

lst = [[0, 0, 0, 0, 0, 1], [1, 2, 3, 4, 5, 4, 3, 0], [1, 4, 5, 6, 7, 0]]

for week in lst:
    print(week)
    for day in week:
        ind = [week.index(day) for day in week if day == 0]
        for i in ind:
            week.pop(i)

print(lst)
0

Use list comprehension

lst = [[x for x in y if x] for y in lst]
-1

Just replace remove by pop and it should work

From https://docs.python.org/3/tutorial/datastructures.html :

list.remove(x)
  • Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
list.pop([i])
  • Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

However i would try the following :

lst = [list(filter(lambda day: day != 0, week)) for week in lst]

or

lst = [[day for day in week if  day != 0] for week in lst]

Sources :

Remove all occurrences of a value from a list?

https://www.w3schools.com/python/python_lists_comprehension.asp

Louis AT
  • 359
  • 1
  • 7