I faced an issue with my code where the loop stops running once it removes the list from the list of list.
data=[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]]
for word_set in data:
if word_set[-1]!="hello":
data.remove(word_set)
print(data)
My desired output is
[['why', 'why', 'hello'], ['why', 'cry', 'hello']]
but the output is
[['why', 'why', 'hello'], ['why', 'hi', 'sllo'], ['why', 'cry', 'hello']]
How do I make the loop go on till the end of the list?
That's because, when you remove the second item (whose index is 1), the items after it move forward. In the next iteration, the index is 2. It should have been pointing to ["why","hi","solo"]. But since the items moved forward, it points to ["why","cry","hello"]. That's why you get the wrong result.
It's not recommended to remove list items while iterating over the list.
You can either create a new list (which is mentioned in the first answer) or use the filter function.
def filter_func(item):
if item[-1] != "hello":
return False
return True
new_list = filter(filter_func, old_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With