Home > Blockchain >  How to add together elements in a tuple?
How to add together elements in a tuple?

Time:09-04

I was wondering how I could add together the elements in each tuple inside a list. Here is my code:

def add_together():

    list = [(2,3), (4,5), (9,10)]
    for tuple in list:
        #missing code goes here I think.
            print('{}   {} = {}'.format(x,y,a))
add_together()

The output I want would start with

2   3 = 5

How do I get that?

CodePudding user response:

You can use tuple-unpacking syntax to get each item in the tuple:

def add_together(lst):
    for (x, y) in lst:
        print('{}   {} = {}'.format(x,y,x y))

lst = [(2,3), (4,5), (9,10)]
add_together(lst)

CodePudding user response:

Try this :

def add_together():
    input_list = [(2,3), (4,5), (9,10)]
    for tup in input_list:
        #missing code goes here I think.
            print('{}   {} = {}'.format(tup[0],tup[1],tup[0] tup[1]))
add_together()

Output :

2   3 = 5
4   5 = 9
9   10 = 19

CodePudding user response:

Also you can use * to unpacking the tuples

def add_together():
    list = [(2, 3), (4, 5), (9, 10)]
    for tupl in list:
        print('{}   {} = {}'.format(*tupl, sum(tupl)))

add_together()

Prints:

2   3 = 5
4   5 = 9
9   10 = 19
  • Related