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!
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.
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.
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.
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 return
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With