How to unpack a list of indefinite length

Question:

I have a list of tuples:

my_lst = [('2.0', '1.01', '0.9'), ('-2.0', '1.12', '0.99')]

I’m looking for a solution to unpack each value so that it prints out a comma separated line of values:

2.0, 1.01, 0.9, -2.0, 1.12, 0.99

The catch is, the lenght of lists vary.

Asked By: nutship

||

Answers:

Use join twice:

>>> lis=[('2.0', '1.01', '0.9'), ('-2.0', '1.12', '0.99')]
>>> ", ".join(", ".join(x) for x in lis)
'2.0, 1.01, 0.9, -2.0, 1.12, 0.99'
Answered By: Ashwini Chaudhary
for i in my_lst:
    for j in i:
        print j, ", "
Answered By: Kyle G.

Use can use itertools chain(..).

>>> from itertools import chain
>>> my_lst = [('2.0', '1.01', '0.9'), ('-2.0', '1.12', '0.99')]
>>> list(chain(*my_lst))
['2.0', '1.01', '0.9', '-2.0', '1.12', '0.99']

And then join them with a “,”.

>>> ",".join(list(chain(*my_lst)))
'2.0,1.01,0.9,-2.0,1.12,0.99'
Answered By: UltraInstinct

There’s also the standard 2-D iterable flattening mechanism:

>>> ', '.join(x for y in lis for x in y)
'2.0, 1.01, 0.9, -2.0, 1.12, 0.99'

Though I prefer chain.from_iterable

Answered By: mgilson

You can use itertools.chain, like so:

list(itertools.chain(*lst))

or use some function like:

def chain(*iters):
    for it in iters:
        for elem in it:
            yield elem
Answered By: pradyunsg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.