Python: use yield commands - how it works
If you're programming with Python, you've probably stumbled across yield commands and generators. This practical tip shows you how you can use it.
Python: Use yield commands - how it works
If you create a list with "list = [1, 2, 3]", you can have the elements output individually using commands such as "for i in list" ↲ "print (i)".
- You can also create a list with the command "list = [x * x for x in range (3)]". Here "list" is an iterable. The practical thing about iterables is that you can have all elements output as often as you like. However, all data is always saved permanently, which can be a hindrance for large amounts of data.
- Generators are similar to iterables, but they can only be run through once, so they do not store the data permanently. Rather, the elements are calculated during operation.
- For example, you can define a generator with the command "testgenerator = (x * x for x in range (3))" and have the elements output with a classic for loop. Alternatively, you can also use the "next (testgenerator)" command. However, this can only iterate once.
- In principle, you can define a generator like a classic function, but a yield statement is used instead of a return statement. Whenever the generator arrives at the yield statement after a run, it executes it and starts a new run. Unlike a return statement, the generator remembers the position and continues with the next yield statement.
- For example, define a generator with the command "def abc ():" ↲ "yield (" A ")" ↲ "yield (" B ")" ↲ "yield (" C ")".
- If you now execute "x = abc ()" once and "next (x)" several times in succession, the letters A, B, and C would be output.
You can find more programming tutorials on our Python programming language topic page. There we show you, for example, how you can easily program a GUI with Python yourself.