
You have to keep in mind that if the generator is empty, i.e.

This would already cost a full iteration cycle.Īnother way to get the next value from a generator is by using the next() function. the amount of lines to read, you need to read the complete file and count the ‘\n’ characters. However, if we use a generator to iterate through a large file, line by line, the generator by definition does not have a length. In this example, we are aware of the length because we have defined it ( range(10)). Generators do not have a length and therefore, you cannot use the length() function. This type of comprehension looks identical to a list comprehension but uses parenthesis instead of brackets and as the name suggests, returns a generator. In the last session, we discussed comprehensions, but we did not mention one special type: the generator comprehension (or generator expression). This is of course only a subtle difference but good to keep in mind. Range() can have repeated full iterations. One thing about generators is that it can only iterate over the iterable once. We have already seen the range() function, this is however officially not a generator (but still a bit similar). When we process the list one (or a couple of) value at a time, it is much smarter to use generators. Regular list need to be allocated all at once and a list of one million values can have a tremendous memory foot print.


This can have benefits in speed, but the biggest benefit is the reduction in memory. We have already come across generators, an iterable that lazily computes the value when it is needed. Feel free to contact me on LinkedIn for questions or requests on particular subjects of Python you want to know about. I try to post an article each day (no promises), starting from the very basics, going up to more complex idioms. This is a series of short 10 minute Python articles helping you to boost your knowledge of Python. A bit more on generators and how to create them
