I want to know how to return values without breaking a loop in Python.
Here is an example:
def myfunction():
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(list)
total = 0
for i in list:
if total < 6:
return i #get first element then it breaks
total += 1
else:
break
myfunction()
return
will only get the first answer then leave the loop, I don't want that, I want to return multiple elements till the end of that loop.
How can resolve this, is there any solution?
You can create a generator for that, so you could yield
values from your generator (your function would become a generator after using the yield
statement).
See the topics below to get a better idea of how to work with it:
An example of using a generator:
def simple_generator(n):
i = 0
while i < n:
yield i
i += 1
my_simple_gen = simple_generator(3) # Create a generator
first_return = next(my_simple_gen) # 0
second_return = next(my_simple_gen) # 1
Also you could create a list
before the loop starts and append
items to that list, then return that list, so this list could be treated as list of results "returned" inside the loop.
Example of using list to return values:
def get_results_list(n):
results = []
i = 0
while i < n:
results.append(i)
i += 1
return results
first_return, second_return, third_return = get_results_list(3)
NOTE: In the approach with list you have to know how many values your function would return in results
list to avoid too many values to unpack
error