How to add together elements in a tuple?

Question:

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?

Asked By: chester

||

Answers:

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
Answered By: Prashant Kumar

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)
Answered By: smac89

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
Answered By: Алексей Р
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.