I have a nested sequence that I want to flatten into a single list of values.
Asked
Active
Viewed 1,071 times
-3
-
1What have you tried, and what exactly is the problem with it? Have you tried researching it, even? I know for a fact that there's more than one question on SO about this already. – jonrsharpe Sep 08 '15 at 16:43
-
I'm going to say "no" to the "Have you tried researching it?" question, considering the first result for this title on Google (other than, now, this question) is [this duplicate](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) which links to two more. – Two-Bit Alchemist Sep 08 '15 at 18:28
2 Answers
2
Please try this general solution: Write a recursive generator function involving a yield from statement. For example:
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x, ignore_types)
else:
yield x
items = [1, 2, [3, 4, [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
print(x)

Fernando Matsumoto
- 2,697
- 1
- 18
- 24

Anna Perelman
- 21
- 1
0
I'd go with recursion but split in a balanced way.
def flatten(lst):
n = len(lst)
if n == 0:
return lst
elif n == 1:
item = lst[0]
try:
return flatten(list(item))
except TypeError:
return [item]
else:
k = n // 2
return flatten(lst[:k]) + flatten(lst[k:])
Demo
items = [1, 2, [3, 4, [5, 6], 7], 8]
flatten(items)
[1, 2, 3, 4, 5, 6, 7, 8]

piRSquared
- 285,575
- 57
- 475
- 624