To return elements of a list from a function

Ans*_*ngh 0 python function list

I want to define a function that takes a list as its argument and then returns the elements in order.

For example:

def iterator(lis):
    for e in range(len(lis)):
        return lis[e]

l=input("Enter list elements:").split()
x=iterator(l)
print(x)
Run Code Online (Sandbox Code Playgroud)

But this just returns the first value of the list as:

Enter list elements:12 23 34
12
Run Code Online (Sandbox Code Playgroud)

How can I print all the values in successive lines?

Pit*_*tto 7

You can use yield in order to build a generator, here's the official documentation about Generators

What is a generator in Python?

A Python generator is a function which returns a generator iterator (just an object we can iterate over) by calling yield. yield may be called with a value, in which case that value is treated as the "generated" value.

I also want to share an example, be sure to read the comments:

def iterator(lis):
    for e in range(len(lis)):
        yield lis[e]

l=input("Enter list elements:").split()

# A generator returns an Iterable so you should
# loop to print
for number in iterator(l):
    print(number)

# Or use list
result = list(iterator(l))
print(result)
Run Code Online (Sandbox Code Playgroud)

Output
1
2
3
['1', '2', '3']