Make a list with non-decreasing order elements of a list in Python

i have a list a = [2,2,1,3,4,1] .
I want to make a new list c with the non-decreasing elements lists of list a.
That means my expected form is -
c = [[2,2],[1,3,4],[1]]

Here is my code:

>>> c = []
>>> for x in a:
...     xx = a[0]
...     if xx > x:
...             b = a[:x]
...             c.append(b)
...             a = a[x:]

but my output is,

>>> c
[[2], [2]]

How can i fix this?

Iā€™m not an expert, but I think you should use a while loop so you could iterate over the elements in the a list.
Then inside the while loop you include if statement to check if the xth element is higher than the xth+1 element, if so, it would add the previous elements until the xth element excluding the xth+1 element. Then it would start checking the elements again in the same way as before, but starting with the xth+1 element.

Iā€™m not sure if my method works, Iā€™m really interested in what others might say.

1 Like

I found this way :grin:

c = []
previous_element = a[0]
sub_list = [previous_element]
for element in a[1:]:
    if previous_element > element:
        sub_list = []
    previous_element = element
1 Like