Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print list of tuples without brackets python

I have a list of tuples and I want to print flattened form of this list. I don't want to transform the list, just print it without parenthesis and brackets.

input: [ ("a", 1), ("b",2), ("c", 3)]
output:   a 1 b 2 c 3

Here's what I do:

l = [ ("a", 1), ("b",2), ("c", 3)]
f = lambda x: " ".join(map(str,x))
print " ".join(f(x) for x in l)

I'm interested in if anybody has a more elegant and possibly a more efficient solution,possibly without doing join, only print. Thanks in advance.

like image 908
dogacanb Avatar asked Aug 25 '26 05:08

dogacanb


2 Answers

from __future__ import print_function 

l =  [("a", 1), ("b",2), ("c", 3)]

print(*(i for j in l for i in j))
a 1 b 2 c 3

Or using itertools.chain to flatten:

from itertools import chain

print(*chain(*l))
like image 94
Padraic Cunningham Avatar answered Aug 26 '26 19:08

Padraic Cunningham


Using str.join() you can use a nested list comprehension:

>>> print ' '.join([str(i) if isinstance(i,int) else i for tup in A for i in tup])
a 1 b 2 c 3

And without join() still you need to loop over the the items and concatenate them, which I think join() is more pythonic way for this aim.

like image 36
Mazdak Avatar answered Aug 26 '26 18:08

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!