Python Forum

Full Version: returning values in for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
in my example i would like to return the whole list with it being in a function instead i am only getting 1 as a return.
However when its not in a function i will get the full list. So my question is how can i put this for loop in a function and have it return all the values if the function is called.

def example():
    list_1 = [1, 2, 3, 4, 5]
    for i in list_1:
        return i

print(example())
Use yield instead of return. This turns example() into a generator, like range(). Then you could do this:
for x in example():
    print(x)
# or
y = list(example())
If you really just want to return the list. Just return the list.
def example():
    return [1, 2, 3, 4, 5]
A function can only return one object. If you want multiple values, you have to return it in a collection object of some sort (list, tuple, set, dict, etc.) In your example, you could return the list directly, or you could return the data in some other object with a copy of the data.

Not sure what is intended by "when not in a function i will get the full list". You can print out multiple things to the screen, so maybe that's what you mean? If you show the code, that might make more sense.
Return statement exits the function. So when it returns 1 from the list, it also exits the function.
Here some examples with yield which as mention make it generator,and doing something to list so it make some senseđź‘€
def example(example):
    for i in list_1:
        yield i ** i

list_1 = [1, 2, 3, 4, 5]
print(example(list_1))
print(list(example(list_1)))
for i in example(list_1):
    print(i)
Output:
<generator object example at 0x03EE8D30> [1, 4, 27, 256, 3125] 1 4 27 256 3125
A generator has a lot power and will take up memory/process(lazy-evaluation) only when it's called.
So if eg itertools.islice can eg calculate only part of result,then power is only used for this parts and not rest of the list.
from itertools import islice

def example(example):
    for i in list_1:
        yield i ** i

list_1 = [1, 2, 3, 4, 5]
print(list(islice(example(list_1), 2 ,4)))
for i in islice(example(list_1),1, 3):
    print(i)
Output:
[27, 256] 4 27