JJson
JJson

Reputation: 233

How to write a function that return a loop?

I would like to know whether a function could return a loop?

My code is as follow:

def looping():
    a = [25,50,75,100, 200, 300]
    for x in a:
        return x
print(looping())

When I print it it returned:

Output:

[25]

Expected output:

25
50
75
100
200
300

Is this possible?

Upvotes: 0

Views: 209

Answers (3)

Kaushik NP
Kaushik NP

Reputation: 6781

It can be done without a loop using just join and map :

>>> print('\n'.join(map(str,a)))

But, if it is a loop that you are looking for, then using return is the wrong way to go about it, as return would give back the control from the function in its first encounter itself.

Instead, use yield or yield from :

yield from iterable is essentially just a shortened form of for item in iterable: yield item

>>> def looping(): 
        a = [25,50,75,100, 200, 300] 
        yield from a

>>> for ele in looping(): 
        print(ele)

#driver values :

IN : a = [25,50,75,100, 200, 300]
OUT: 25
     50
     75
     100
     200
     300

Upvotes: 1

abarnert
abarnert

Reputation: 365707

First, the problem with your existing code is that once you return, the function is over. So, you just return the first value and you're done.


A function can't return a loop, because a loop isn't a kind of value.

A function can return an iterable, which is a value that can be looped over. There are a few ways to do this:


You could use yield, as in most of the other answers, to make your function a generator function, so it returns an iterator over all of the things you yield.

But yielding inside a loop is just a clumsy way of doing yield from, so really, you should just do that:

def looping():
    a = [25, 50, 75, 100, 200, 300]
    yield from a
for x in looping():
    print(x)

You can instead return an iterator directly:

def looping():
    a = [25, 50, 75, 100, 200, 300]
    return iter(a)
for x in looping():
    print(x)

Or, most simply of all: a sequence, like a list, is just as iterable as an iterator. So, if you have a list, just return it:

def looping():
    a = [25, 50, 75, 100, 200, 300]
    return a
for x in looping():
    print(x)

While we're at it, you don't even really need an explicit loop there. You can call a function that hides the loop inside, like join:

print('\n'.join(looping()))

Or you can even splat the iterable directly to print:

print(*looping(), sep='\n')

Although in this case, I think the loop is perfectly reasonable, so if you're happy with it, stick with it.

Upvotes: 6

Spasel Togalk
Spasel Togalk

Reputation: 99

If you merely want to output the contents of a list, you may use the .join() feature.

print("\n".join([str(x) for x in a]))

If you want to utilize loops, use a generator, and write the loop outside as shown.

def looping():
    a = [25, 50, 75, 100, 200, 300]
    for x in a:
        yield x

for x in looping():
    print(x)

Upvotes: 2

Related Questions