How to print a list of tuples with no brackets in Python
Asked Answered
S

5

23

I'm looking for a way to print elements from a tuple with no brackets.

Here is my tuple:

mytuple = [(1.0,),(25.34,),(2.4,),(7.4,)]

I converted this to a list to make it easier to work with

mylist = list(mytuple)

Then I did the following

for item in mylist:
    print(item.strip())

But I get the following error

AttributeError: 'tuple' object has no attribute 'strip'

Which is strange because I thought I converted to a list?

What I expect to see as the final result is something like:

1.0,
25.34,
2.4,
7.4

or

1.0, ,23.43, ,2.4, ,7.4 
Swetiana answered 1/10, 2013 at 9:34 Comment(1)
you actually want those double commas?Charlettecharley
B
23

mytuple is already a list (a list of tuples), so calling list() on it does nothing.

(1.0,) is a tuple with one item. You can't call string functions on it (like you tried). They're for string types.

To print each item in your list of tuples, just do:

for item in mytuple:
    print str(item[0]) + ','

Or:

print ', ,'.join([str(i[0]) for i in mytuple])
# 1.0, ,25.34, ,2.4, ,7.4
Berlioz answered 1/10, 2013 at 9:36 Comment(2)
would print ', ,'.join(map(str, mytuple)) do the same ?Fusil
@Fusil Nope as we need i[0] for i and not i for iBerlioz
S
20

You can do it like this as well:

mytuple = (1,2,3)
print str(mytuple)[1:-1]
Seniority answered 11/1, 2017 at 23:50 Comment(0)
M
9
mytuple = [(1.0,),(25.34,),(2.4,),(7.4,)]
for item in mytuple:
    print(*item) # *==> unpacking 
Matrices answered 22/11, 2017 at 7:38 Comment(0)
R
1

I iterate through the list tuples, than I iterate through the 'items' of the tuples.

my_tuple_list = [(1.0,),(25.34,),(2.4,),(7.4,)]

for a_tuple in my_tuple_list:  # iterates through each tuple
    for item in a_tuple:  # iterates through each tuple items
        print item

result:

1.0
25.34
2.4
7.4

to get exactly the result you mentioned above you can always add

print item + ','
Rilda answered 12/1, 2017 at 0:37 Comment(0)
C
0

One can generalize to any complex structure with use of recursion:

def flatten(o):
    if not isinstance(o, (list, tuple, dict)):
        return str(o)
    elif isinstance(o, (list, tuple)):
        return "\n".join(flatten(e) for e in o)
    elif isinstance(o, (dict)):
        return "\n".join(e + ": " + flatten(o[e]) for e in o)

Example:

>>> flatten((1, [21, {'a': 'aaa', 'b': 'bbb'}], 3))
'1, 21, a: aaa\nb: bbb, 3'
Cimon answered 10/2, 2022 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.