user12637176
user12637176

Reputation: 47

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.

Upvotes: 1

Views: 555

Answers (2)

L.Grozinger
L.Grozinger

Reputation: 2398

It is hard to formulate a solution using break here.

May I suggest that you rewrite your psuedo-algorithm a little more concisely first. Something like:

  1. For every item in the input list, append it to an output list.
  2. If the item is odd then remember the current output list, and start a new one.

Then, implemented in Python it looks like:

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

for x in input_list:
    output_list[-1].append(x)
    if x % 2 != 0:
        output_list.append([])

Upvotes: 0

lazy.coder
lazy.coder

Reputation: 461

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)

Upvotes: 1

Related Questions