1

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.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
Rakesh Nittur
  • 445
  • 1
  • 7
  • 20

5 Answers5

4

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

kmario23
  • 57,311
  • 13
  • 161
  • 150
2

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.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
1

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]]))
ccQpein
  • 705
  • 7
  • 20
0

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']
Reck
  • 1,388
  • 11
  • 20
0

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']
Community
  • 1
  • 1
LetzerWille
  • 5,355
  • 4
  • 23
  • 26