Rakesh Nittur
Rakesh Nittur

Reputation: 475

Split elements of a list inside a list in python

I am new to Python. How can I make a single list out of many lists inside a list?
For example,

list1 = ['aplle', 'grape', ['aplle1', 'grape1'] ]

Output should be:

list1 = ['aplle', 'grape', 'aplle1', 'grape1']

The list has thousands of elements.

Upvotes: 1

Views: 1717

Answers (5)

LetzerWille
LetzerWille

Reputation: 5658

I like this solution from Cristian, it is very general. flatten

def flatten(l):
import collections
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            for sub in flatten(el):
                yield sub
        else:
            yield el


print(list(flatten(['aplle', 'grape', ['aplle1', 'grape1']])))

['aplle', 'grape', 'aplle1', 'grape1']

Upvotes: 0

kmario23
kmario23

Reputation: 61305

use flatten in compiler.ast:

>>>> from compiler.ast import flatten
>>>> list1 = ['apple', 'grape', ['apple1', 'grape1', ['apple2', 'grape2'] ] ]
>>>> flattened_list = flatten(list1)

Output:
['apple', 'grape', 'apple1', 'grape1', 'apple2', 'grape2']

This will work for multiple nesting levels

PS: But this package has been removed in Python3

Upvotes: 4

Reck
Reck

Reputation: 1436

Here is working solution for splitting elements of the list inside list in order of the list.

Input List :

list1 = ['aplle', 'grape', ['aplle1', 'grape1'],'apple3',['apple2','grape2'] ]

Here is the code:

for obj in list1:
    if type(obj) is list:
        i = list1.index(obj)
            for obj1 in obj:
                list1.insert(i,obj1)
            list1.remove(obj)

Ouput List in order as needed :

list1 = ['aplle', 'grape', 'grape1', 'aplle1', 'apple3', 'grape2', 'apple2']

Upvotes: 0

ccQpein
ccQpein

Reputation: 815

That's worked

def main(lis):
    new_list = []
    for i in lis:
        if type(i) != list:
            new_list.append(i)
        else:
            for t in range(len(i)):
                new_list.append(i[t])
    return new_list

if __name__ == '__main__':
    print(main([1,2,3,[4,5]]))

Upvotes: 1

Paul Boddington
Paul Boddington

Reputation: 37645

I'm new to python too, so there's probably a simpler way, but this seems to work.

list1 = ['aplle', 'grape', ['aplle1', 'grape1'] ]
list2 = []
for x in list1:
    list2 += x if type(x) == list else [x]
print(list2)

This will not work if the list has elements that are themselves nested lists, but I think it meets the requirements of the question.

Upvotes: 2

Related Questions