ela rednax
ela rednax

Reputation: 73

how to return two values in a tuple in python function

i need to solve a task: a function filter_list that takes only one argument (a list of integers) and returns two values in a tuple

  1. sum of elements of the list that are >= 13 and <= 97
  2. sum of elements of the list that are >0 and 13-fold

So i have a conceptual understanding of how that could be achieved, however when i start writing my code, i can't assign those two values to a new variable outside the function.

numbers = [1, 10, 13, 23, 34, 45, 90]

    def filter_list(nums):
        for e in nums:
            result1 = sum(e for e in nums if e >= 13 and e <= 97)
            return result1
        for e in nums:
            result2 = sum(e for e in nums if e>0 and e % 13 == 0)
            return result2
        print(result1, result2)
    
print(filter_list(numbers))

result_sum = filter_list(numbers)

print(result_sum)

Upvotes: 0

Views: 970

Answers (2)

Raghul Thangavel
Raghul Thangavel

Reputation: 128

def filter_list(nums):
    for e in nums:
        result1 = sum(e for e in nums if e >= 13 and e <= 97)
        result2 = sum(e for e in nums if e>0 and e % 13 == 0)
    return (result1,result2)

numbers = [1, 10, 13, 23, 34, 45, 90]

result_sum = filter_list(numbers)

print(result_sum)

Output : (205, 13)

I have just done a small correction in your code.

A function won't execute after a return statement.

In your case the function returns the result1 and get backs to the main code.

Edit:

 def filter_list(nums):
    result1 = sum(e for e in nums if e >= 13 and e <= 97)
    result2 = sum(e for e in nums if e>0 and e % 13 == 0)
return (result1,result2)

numbers = [1, 10, 13, 23, 34, 45, 90]

result_sum = filter_list(numbers)

print(result_sum)

Output : (205, 13)

Upvotes: 1

thethiny
thethiny

Reputation: 1258

def filter_list(nums):
    result1 = sum(e for e in nums if 97 >= e >= 13)
    result2 = sum(e for e in nums if e > 0 and e % 13 == 0)
    print(result1, result2)
    return result1, result2

You don't need to do a for loop then inside it another. Also after you return the function is exited and you can no longer do anything. So you have to store the variables then return them at once.

Upvotes: 3

Related Questions