How to Use 'Return' to Get Back Multiple Values from a for Loop? How to Put Them in a List

How can I use `return` to get back multiple values from a loop? Can I put them in a list?

Using a return inside of a loop will break it and exit the function even if the iteration is still not finished.

For example:

def num():
# Here there will be only one iteration
# For number == 1 => 1 % 2 = 1
# So, break the loop and return the number
for number in range(1, 10):
if number % 2:
return number
>>> num()
1

In some cases we need to break the loop if some conditions are met. However, in your current code, breaking the loop before finishing it is unintentional.

Instead of that, you can use a different approach:

Yielding your data

def show_todo():
# Create a generator
for key, value in cal.items():
yield value[0], key

You can call it like:

a = list(show_todo())  # or tuple(show_todo())

or you can iterate through it:

for v, k in show_todo(): ...

Putting your data into a list or other container

Append your data to a list, then return it after the end of your loop:

def show_todo():
my_list = []
for key, value in cal.items():
my_list.append((value[0], key))
return my_list

Or use a list comprehension:

def show_todo():
return [(value[0], key) for key, value in cal.items()]

Return Multiple List Values in Loop

Replace return with yield to turn your function into a generator function. When you call it, it returns a generator object that you can iterate over at your leisure to produce the results you want one at a time:

def listIterations(inputcsv):
for i in inputcsv:
yield str(i)
>>> listIterations(my_list)
<generator object listIterations at 0x00000237062CC350>

You will only be able to use this object once. Since your input is a list, you can always call listIterations multiple times to get a new generator. To print, do a star-expand of the generator:

print(*listIterations(my_list), sep='\n')

Expanding the generator into an argument list will run it, and pass each element in to print. If you want to have a permanent record of the generated values, expand them into a list:

generated_values = list(listIterations(my_list))

or a tuple:

generated_values = tuple(*listIterations(my_list))

You can print the stashed values the same way:

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

All that being said, if you just need an iterator over a list, you can obtain one using the builtin iter:

iter(my_list)

This is equivalent (for a list) to:

def listIterations(somelist):
yield from somelist
listIterations(my_list)

Returning multiple values in a for loop?

It is because card is getting overwritten in each iteration and you only return the last value.

You can create a list and return the list instead:

def draw(x):
random_cards = []
for c in range(0, x):
card = random.choice(cards)
random_cards.append(card)
return random_cards

user_hand.extend(draw(1)) # further you'll need extend here else it will create a list of lists

Returning multiple values from a loop w/o getting the None

You can only return once from a function. So the best would be to collect your result in a list and return the list:

from random import randint

def sec_num(count=5):
return [randint(0, 999999) for _ in range(count)]

for num in sec_num():
print("%06d" % num)

Output:

710690
816475
087483
572131
292748

Looks like you don't access self. Therefore, you don't need a class for the case you show in your example. Going with simple function seems preferable here.

If you have many second prices, say a million or so, you can make your function more efficient using yield. This would turn your function into a generator. This is a whole new concept to understand and ne need for case but worthwhile to explore when you get deeper into Python.

Return multiple values to main function from a for loop in another function in Python

Take the return statement out of the loop. You don't want to return until you've finished concatenating all the items.

You can also replace the loop with a list comprehension and the join function.

return "".join(str(item) for item in mf)


Related Topics



Leave a reply



Submit