0

How can I loop through all the elements in a list of tuples, into an empty list?

For example:

tup_Before = [(69592, 69582), (69582, 69518), (69518, 69532), (69532, 69525)]

tup_After = [69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]
Chris Martin
  • 29,484
  • 8
  • 71
  • 131
Nobi
  • 1,063
  • 2
  • 25
  • 39
  • a trivial reduce : `list(reduce(lambda x, y: x + y, tup_Before))` (the lambda can be replaced by `operator.__add__` for readability) – njzk2 Mar 25 '14 at 18:49

3 Answers3

1

A list comprehension:

tup_after = [v for t in tup_Before for v in t]

or use itertools.chain.from_iterable():

from itertools import chain
tup_after = list(chain.from_iterable(tup_Before))

Demo:

>>> tup_Before = [(69592, 69582), (69582, 69518), (69518, 69532), (69532, 69525)]
>>> [v for t in tup_Before for v in t]
[69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]
>>> from itertools import chain
>>> list(chain.from_iterable(tup_Before))
[69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
0

also, the least clear answer:

[l for l in l for l in l]

where l is your list name

acushner
  • 8,972
  • 1
  • 32
  • 32
0

You can try using itertools.chain() and unpacking with *:

import itertools

new_tup = list(itertools.chain(*tup_before))

Demo:

>>> print new_tup
[69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]
Christian Tapia
  • 32,670
  • 6
  • 50
  • 72