Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 619
user2240542 Avatar asked Feb 11 '26 12:02

user2240542


2 Answers

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))
    
like image 70
Andrew Clark Avatar answered Feb 13 '26 01:02

Andrew Clark


s = (4,8,9), (1,2,3), (4,5,6)
print tuple([sum(x) for x in s])
like image 21
A. Rodas Avatar answered Feb 13 '26 03:02

A. Rodas



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!