Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python iterating through pair of values in list for function

Tags:

python-3.x

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!

like image 729
lukas Avatar asked Aug 25 '18 02:08

lukas


People also ask

How do you iterate through a pair in a list Python?

combinations: A better way to iterate through a pair of values in a Python list. If you want to iterate through a pair of values in a list and the order does not matter ( (a,b) is the same as (b, a) ), use itertools. combinations instead of two for loops.

How do you loop a list in a function Python?

We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list. The output would be the same as above.

Can you iterate through a function in Python?

For example, open files in Python are iterable. As you will see soon in the tutorial on file I/O, iterating over an open file object reads data from the file. In fact, almost any object in Python can be made iterable. Even user-defined objects can be designed in such a way that they can be iterated over.


2 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)
like image 50
Deepak Saini Avatar answered Nov 15 '22 07:11

Deepak Saini


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
like image 40
ggorlen Avatar answered Nov 15 '22 08:11

ggorlen