What does the “yield” keyword do?

DWQA QuestionsCategory: PythonWhat does the “yield” keyword do?
Editor Staff asked 2 months ago

What does the “yield” keyword do?

5 Answers
Editor Staff answered 2 months ago

To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables.

Iterables

When you create a list, you can read its items one by one. Reading its items one by one is called iteration:

>>> mylist = [1, 2, 3]
>>> for i in mylist:
...    print(i)
1
2
3

mylist is an iterable. When you use a list comprehension, you create a list, and so an iterable:

>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
...    print(i)
0
1
4

Everything you can use “for... in...” on is an iterable; listsstrings, files…
These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.

Editor Staff answered 2 months ago

yield is a keyword that is used like return, except the function will return a generator.

Editor Staff answered 2 months ago

yield is a keyword that is used like return, except the function will return a generator.

Editor Staff answered 2 months ago

yield

Editor Staff answered 2 months ago

python