What is the most Pythonic way of removing the list-in-list hierarchy?
That is, from
A=[[(1, 1), (2, 2)],[(1, 1), (2, 2), (3, 3)], [(1, 1)]]
to
B=[(1, 1), (2, 2), (1, 1), (2, 2), (3, 3), (1, 1)]
What is the most Pythonic way of removing the list-in-list hierarchy?
That is, from
A=[[(1, 1), (2, 2)],[(1, 1), (2, 2), (3, 3)], [(1, 1)]]
to
B=[(1, 1), (2, 2), (1, 1), (2, 2), (3, 3), (1, 1)]
import operator
reduce(operator.add, A)
or
reduce(lambda x,y:x+y, A)
Its more Pythonic to use chain.from_iterable to unwrap a nested list
>>> from itertools import chain
>>> list(chain.from_iterable(A))
[(1, 1), (2, 2), (1, 1), (2, 2), (3, 3), (1, 1)]
"most pythonic" can be debated endlessly. I prefer a nested list comprehension to flatten nested lists.
B = [element for sublist in A for element in sublist]
When it comes down to it, use what is most readable to you since you're likely the person who has to interface with your code most often.
import itertools
a = [[(1, 1), (2, 2)],[(1, 1), (2, 2), (3, 3)], [(1, 1)]]
list(itertools.chain(*a))
Check out the itertools module. Lot's of good stuff.