Dec-28-2017, 05:53 PM
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?
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']