Search code examples
pythonnested-lists

How to split list into nested lists with the same first value?


I have python list (example):

mylist = ["AA - AA", "qwerty", "123456789", "nvidia", "fan", "8765", "AA - AA", "group", "bread", "plate", "knife", "AA - AA", "123123123", "laptop", "666"]

(My real list contains for about 2000 elements, what you see above is just a short example.)

I need to split that list into:

newlist = [["AA - AA", "qwerty", "123456789", "nvidia", "fan", "8765"], ["AA - AA", "group", "bread", "plate", "knife"], ["AA - AA", "123123123", "laptop", "666"]]

As you can see, each nested list has a different number of elements and the same first element "AA - AA".

How can I split a list into nested lists, so that it has the first element "AA - AA" and the last element (the element before the next "AA - AA")?


Solution

  • Assuming the first element in mylist is 'AA - AA' then:

    mylist = ["AA - AA", "qwerty", "123456789", "nvidia", "fan", "8765", "AA - AA", "group", "bread", "plate", "knife", "AA - AA", "123123123", "laptop", "666"]
    
    result = []
    
    for e in mylist:
        if e == 'AA - AA':
            result.append([e])
        else:
            result[-1].append(e)
    
    print(result)
    

    Output:

    [['AA - AA', 'qwerty', '123456789', 'nvidia', 'fan', '8765'], ['AA - AA', 'group', 'bread', 'plate', 'knife'], ['AA - AA', '123123123', 'laptop', '666']]
    

    Note:

    There's certainly no need for itertools, numpy or temporary/intermediate variables for something so trivial