Search code examples
pythonpython-2.7list-manipulation

How to make multiple list from one list in python


I want to make the multiple list from one list on condition base.

Actual data:

numbers = [1, 2, 3,4,5,6,7,8,9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34 ,5 ,6 ,7,78]

Expected outcome:

[1, 2, 3,4,5,6,7,8,9]
[1, 11, 12, 13]
[1, 21, 22, 25, 6]
[1, 34 ,5 ,6 ,7,78]

Here is my attempt:

list_number=[]
numbers = [1, 2, 3,4,5,6,7,8,9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34 ,5 ,6 ,7,78]
for x in numbers:
    if x==1:
        list_number.append(numbers)

print list_number[0] 

Solution

  • Rather than adding new references/copies of the original numbers to the list, either start a new list whenever you see a 1 or add to the latest one otherwise:

    list_number = []
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34, 5, 6, 7, 78]
    for x in numbers:
        if x==1:
            list_number.append([1])
        else:
            list_number[-1].append(x)
    
    print list_number
    

    Result:

    >>> for x in list_number:
    ...     print x
    ...
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    [1, 11, 12, 13]
    [1, 21, 22, 25, 6]
    [1, 34, 5, 6, 7, 78]