Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over list of list python

Tags:

python

loops

list

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?

like image 805
Nobuj Avatar asked Aug 05 '26 07:08

Nobuj


1 Answers

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)
like image 133
sunhs Avatar answered Aug 07 '26 22:08

sunhs