Python Forum

Full Version: List of List into List
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do you make this list ['Tokyo','London',['Paris','Madrid']] into this list ['Tokyo','London','Paris','Madrid']?
Taking a nested data structure, with multiple levels, and turning it into a single level, is known as "flattening".  There's many ways to do it, recursion is (I think) the way that's normally suggested, that way it can handle a list within a sublist within the list.

Maybe like this?
>>> cities = ["Tokyo", "London", ["Paris", "Madrid"]]
>>> def flatten(items):
...   for item in items:
...     if isinstance(item, list):
...       yield from flatten(item)
...     else:
...       yield item
...
>>> list(flatten(cities))
['Tokyo', 'London', 'Paris', 'Madrid']
It would be nice if you provide more information on how do you get this structure, i.e. it may be a problem with how you create it in the first place.
I was just practicing some stuff on list comprehensions and wanted to see how you go about using list comprehensions to create a single list from a list of list where at least one of the elements in the list is not necessarily an element within a sub-list

For example, it was easy for me to create a single list using list comprehension from the following list [['Tokyo','London'],['Madrid','Paris']], you could simply do:

>>>oList= [['Tokyo','London'],['Madrid','Paris']]
>>>newList = [item for sublist in oList for item in sublist]
>>>newList
['Tokyo', 'London', 'Madrid', 'Paris']
but how would you go about using list comprehensions to create a single list when you have a list like this ['Tokyo','London',['Madrid','Paris']] - makes the problem a little more difficult because using the above approach yields the following result (which is wrong):

>>> oList = ['Tokyo','London',['Madrid','Paris']]
>>> newList = [item for sublist in oList for item in sublist]
>>> newList
['T', 'o', 'k', 'y', 'o', 'L', 'o', 'n', 'd', 'o', 'n', 'Madrid', 'Paris']
I hope that clarifies my problem and would appreciate it if anyone out there knows how to solve this using list comprehensions.
Thank You.
The first step, is getting all the items to be the same:
>>> oList = ['Tokyo','London',['Madrid','Paris']]
>>> [item if isinstance(item, list) else [item] for item in oList]
[['Tokyo'], ['London'], ['Madrid', 'Paris']]
From there, you can use what you already have:
>>> oList = ['Tokyo','London',['Madrid','Paris']]
>>> [subitem for item in [x if isinstance(x, list) else [x] for x in oList] for subitem in item]
['Tokyo', 'London', 'Madrid', 'Paris']
more examples
newList = [item for items in oList for item in [[items], items][isinstance(items, list)]]
newList = [item for items in oList for item in (items if isinstance(items, list) else [items])]
is_list = lambda l: l if isinstance(l, list) else [l]
newList = [item for items in oList for item in is_list(items)]