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
CodePudding user response:
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]]
CodePudding user response:
It's considered a bad practice to remove/delete an item while looping over a sequence (list, eg). You could try List Comprehension or looping from the backward of sequence.
So the simple fix is to change this line only:
for week in lst:
# week is a list
for day in week[::-1]:
if day == 0:
week.remove(day)
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
Use list comprehension
lst = [[x for x in y if x] for y in lst]