Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List of List into List
#4
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.
Reply


Messages In This Thread
List of List into List - by mp3909 - Dec-28-2017, 05:16 PM
RE: List of List into List - by nilamo - Dec-28-2017, 05:53 PM
RE: List of List into List - by buran - Dec-28-2017, 07:06 PM
RE: List of List into List - by mp3909 - Dec-28-2017, 08:29 PM
RE: List of List into List - by nilamo - Dec-28-2017, 08:51 PM
RE: List of List into List - by Windspar - Dec-28-2017, 10:13 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to capitalize letter in list object Python iwonkawa 4 205 May-29-2024, 04:29 PM
Last Post: DeaD_EyE
  remove duplicates from dicts with list values wardancer84 27 861 May-27-2024, 04:54 PM
Last Post: wardancer84
  what to return for an empty list Skaperen 2 259 May-24-2024, 05:17 PM
Last Post: Skaperen
  Extending list doesn't work as expected mmhmjanssen 2 285 May-09-2024, 05:39 PM
Last Post: Pedroski55
  Strange behavior list of list mmhmjanssen 3 455 May-09-2024, 11:32 AM
Last Post: mmhmjanssen
  Sort a list of dictionaries by the only dictionary key Calab 2 733 Apr-29-2024, 04:38 PM
Last Post: Calab
  element in list detection problem jacksfrustration 5 590 Apr-11-2024, 05:44 PM
Last Post: deanhystad
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 375 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  PyYAML read list of int zisco 2 434 Apr-02-2024, 12:36 PM
Last Post: zisco
  list.sort() returning None SmallCoder14 8 801 Mar-19-2024, 09:49 PM
Last Post: SmallCoder14

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020