Dec-28-2017, 08:29 PM
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Â
Thank You.
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.