Vomer
Vomer

Reputation: 97

How come my code only returns the first element from my list?

How come when I call the function I get only the first element from the list printed, but when I replace "return" for "print" inside the function and then call it I get the full list?

def show_magicians(magicians):

    for magician in magicians:
        return(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))

Upvotes: 0

Views: 1209

Answers (3)

Dave748
Dave748

Reputation: 30

You could try this instead:

def show_magicians(magicians):

    for magician in magicians:
        yield(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
for mag in show_magicians(magicians):
    print(mag, end=' ')

Instead of running through the loop and returning the first iteration this will turn your code into a generator that you can put in another loop like shown. Using yield instead of return will return each item in the list then continue to the next item then return that and the next and so on and so on.

Just in case you don't know the end=' ' in the print function is what is used to separate each item as it is returned. Play with it by replacing ' ' with ',' or '\n' etc for different results. You can even append the results to a new list and print that instead but, again, you'll just end up with a copy of the original list.

Upvotes: 1

user5640319
user5640319

Reputation:

You can reach your goal by creating an empty list inside your function and appending it.

Like so:

def show_magicians(magicians):

    new_list = []
    for magician in magicians:
        new_list.append(magician)

    return new_list

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))

But then you'd be returning the list with same values as your argument.

Upvotes: 0

ncica
ncica

Reputation: 7206

The print() function writes, i.e., "prints", a string in the console. The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.

In first iteration when code reach return it go out of function, because of that iterates just one time

Upvotes: 1

Related Questions