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)]
Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174

4 Answers4

2
import operator
reduce(operator.add, A)

or

reduce(lambda x,y:x+y, A)
waitingkuo
  • 89,478
  • 28
  • 112
  • 118
  • Awesome, it works! But would you mind explaining a bit? What is the rationale behind this – Sibbs Gambling Oct 11 '13 at 03:19
  • You can take a look at [reduce](http://docs.python.org/2/library/functions.html#reduce). And in this case, `operator.add` means lambda x,y:x+y – waitingkuo Oct 11 '13 at 03:23
  • 2
    **Note**, reduce has been deprecated and removed in Python 3.x. You would then need to use [functools.reduce](http://docs.python.org/2/library/functools.html#functools.reduce) – Abhijit Oct 11 '13 at 03:38
2

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)]
Abhijit
  • 62,056
  • 18
  • 131
  • 204
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.

roippi
  • 25,533
  • 4
  • 48
  • 73
1
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.

Lucas Ribeiro
  • 6,132
  • 2
  • 25
  • 28