Yields and List in Python
In this article, i will compare two common ways to return a sequence of values from a function is using yield to create a generator and returning a list.
What is List returning?
Returning a list from a function is returning a sequence of values (list of integers, list of strings, etc). The caller receives the fully constructed and can iterate over it or manipulate it as needed.
def return_list(nums):
res = []
for i in range(nums):
res.append(i)
return res
my_list = return_list(5)
print(my_list)
# Output: [0, 1, 2, 3, 4]
What is yield?
yield is a keyword in Python used to create a generator. It allows a function return a value and pause its execution, saving its state for later resumption. When the function is called, it returns a generator object which can be iterated over to retrieve values one at a time.
def generate_numbers(nums):
for i in range(nums):
yield i
my_yield = generate_numbers(5)
for num in my_yield:
print(num, end=' ')
#Output: 0 1 2 3 4
What is the difference?
Memory usage:
Performance:
Easy to use:
Conclusion
Choosing the right method depends on the specific requirements of your tasks, particularly regarding memory usage, performance, and ease of use. Understanding both methods is an important skill for any Python developer.
Very helpfull! Thanks.