Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List of List into List
#2
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']
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
  Extending list doesn't work as expected mmhmjanssen 2 236 May-09-2024, 05:39 PM
Last Post: Pedroski55
  Strange behavior list of list mmhmjanssen 3 392 May-09-2024, 11:32 AM
Last Post: mmhmjanssen
  Sort a list of dictionaries by the only dictionary key Calab 2 686 Apr-29-2024, 04:38 PM
Last Post: Calab
  element in list detection problem jacksfrustration 5 530 Apr-11-2024, 05:44 PM
Last Post: deanhystad
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 334 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  PyYAML read list of int zisco 2 392 Apr-02-2024, 12:36 PM
Last Post: zisco
  list.sort() returning None SmallCoder14 8 731 Mar-19-2024, 09:49 PM
Last Post: SmallCoder14
  append str to list in dataclass flash77 6 643 Mar-14-2024, 06:26 PM
Last Post: flash77
  Help with to check an Input list data with a data read from an external source sacharyya 3 522 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  list and operator * akbarza 1 306 Feb-29-2024, 08:10 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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