Skip to content
Advertisement

How to create a new list everytime you loop and repeat the loop after appending elements to it?

This is my list

lst = [1,2,3,4,4,5,6,7,8,8,9,9,10,1]

I want this output

[1][2,3][4,4,5][6,7][8,8,9][9][10,1]

If the number is even and the next number is odd loop should break, and the next odd or even number should be appended in another list. if there is even number, the list shouldn’t be broken until the next odd is found.

Advertisement

Answer

lis = [1,2,3,4,4,5,6,7,8,8,9,9,10,1] 
tempList = []
result = []
for item in lis:
    tempList.append(item)
    if item % 2 == 1:
        result.append(tempList)
        tempList = []
print(result)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement