0

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)
1
  • Once you hit a return statement the function exits and won't continue running. So for the first iteration of your first for loop, it will exit. It will never reach any other iteration and it certainly won't hit the second for loop. Commented Mar 14, 2021 at 13:13

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

Comments

1
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)

2 Comments

You have a problem in your code, which is similar to the problem in his code, which is the double for loop concept. You don't need the first for loop if you're summing the internal loop.
I'm sorry, i didn't concentrate on logic, just trying to make a clear in functions, thanks mate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.