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
  • 30,334
  • 10
  • 78
  • 137
Nobi
  • 1,113
  • 4
  • 23
  • 41
  • 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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

also, the least clear answer:

[l for l in l for l in l]

where l is your list name

acushner
  • 9,595
  • 1
  • 34
  • 34
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
  • 33,620
  • 7
  • 56
  • 73