Python iterating through pair of values in list for function

Viewed 489

I have a list like

cases = [(1,1), (2,2), (3,3)]

trying to write a function that calculates through each item and return values:

def case_cal(cases)
    for x, y in cases:
        result = x+y
        return result

output = case_cal(cases)
print(output)

I like to get output like

2
4
6

But I only get

2

I am a newbie learning python and something simple I am missing here. Could I get any advice? Thanks in advance!

6 Answers

Once you return something you move out of the function. So make a list, append your values to the list and then return in the end.

def case_cal(cases):
    ret_values = []
    for x, y in cases:
        result = x+y
        ret_values.append(result)
    return ret_values

output = case_cal(cases)
print(*output)

Your code returns inside the for loop, at the end of the first iteration, so you'll only see the first x + y result.

This is a perfect use for a generator, which will allow you to grab the next x + y calculation on demand and offer maximum control over what the caller can do with the result:

cases = [(1,1), (2,2), (3,3)]

def case_cal(cases):
    for x, y in cases:
        yield x + y

for x in case_cal(cases):
    print(x)

Output:

2
4
6

You can simply map the items of the list to the sum function:

list(map(sum, cases))

This becomes:

[2, 4, 6]

Or if you want to print the items individually:

for s in map(sum, cases):
    print(s)

This outputs:

2
4
6

If you dont need the values in a list you can procced as follows:

cases = [(1,1), (2,2), (3,3)]

def case_cal(cases):
    for x, y in cases:
        result = x+y
        print(result)

case_cal(cases)

Just directly print the values instead of returning them as once you return something you move out of the function.
Also,

cases = [(1,1), (2,2), (3,3)]

def case_cal(cases):
    for x, y in cases:
        print(x+y)

case_cal(cases)

You could do this:

cases = [(1,1), (2,2), (3,3)]

def case_cal(cases):
    results = []
    for x, y in cases:
        results.append(x + y)
    return results

output = [case_cal(cases)]
print(output)

And then you could define a print function like this:

def print_cases(cases):
    for elem in cases[0]:
        print(elem)

But there is a more Pythonic way:

def case_cal(cases):
    return [(x + y) for (x, y) in cases]

This is called a list comprehension, and you are going to be using them very often in python. You can read more about them here.

Simply do the following:

def case_calc(cases):
    for x, y in cases:
        print(x + y)

case_calc([(1, 1), (2, 2), (3, 3)])

Cheers

Related