user2240542
user2240542

Reputation: 79

How to print a for loop as a list

So I have:

s = (4,8,9), (1,2,3), (4,5,6)
for i, (a,b,c) in enumerate(s):
    k = [a,b,c]  
    e = k[0]+k[1]+k[2]
    print e

It would print:

21
6
15

But I want it to be:

(21,6,15)

I tried using this but it's not what I wanted:

print i,

So is this possible?

Upvotes: 2

Views: 134

Answers (4)

hd1
hd1

Reputation: 34657

>>> l = []
>>> for i, (a,b,c) in enumerate(s):
...     k = [a,b,c]  
...     e = k[0]+k[1]+k[2]
...     l.append(e)
... 
>>> print l
[21, 6, 15]

I do hope this helps. You're appending the sum of list k to list l and finally printing it out.

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208465

Here are a few options:

  • Using tuple unpacking and a generator:

    print tuple(a+b+c for a, b, c in s)
    
  • Using sum() and a generator:

    print tuple(sum(t) for t in s)
    
  • Using map():

    print tuple(map(sum, s))
    

Upvotes: 9

A. Rodas
A. Rodas

Reputation: 20679

s = (4,8,9), (1,2,3), (4,5,6)
print tuple([sum(x) for x in s])

Upvotes: 1

Marcin
Marcin

Reputation: 49826

print always prints a new line. If you want to print one line, you need to do your printing all at once.

Inside your loop, create a string, and print that. Or, given how you want it formatted, you could also create a tuple (which is represented with round brackets, as you have).

Incidentally, if you want to add the members of a list, you can just use sum:

e = sum(k)

Also, s is already a tuple, you don't need to enumerate it - you can just loop over it with:

for k in s:
    e = sum(k)

Now, go ahead and put that all together.

Upvotes: 0

Related Questions