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
  • 18,128
  • 38
  • 90
  • 168

4 Answers4

2
import operator
reduce(operator.add, A)

or

reduce(lambda x,y:x+y, A)
waitingkuo
  • 80,738
  • 23
  • 108
  • 117
  • 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
  • 59,056
  • 16
  • 119
  • 195
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
  • 24,635
  • 4
  • 45
  • 71
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
  • 5,864
  • 2
  • 23
  • 28