Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- When people use collections of any kind in Python, most of the people rely on lists
- That's fine, but can we use something better than lists?
- Generators are a pretty nice feature of Python.
- Instead of generating the full collection if we use lists, using generators we create context-aware objects that are iterable only once, but have a great advantage of generating sequence items on demand vs all at once.
- This can be very helpful in a memory constrained environment.
- So, simple example:
- even_numbers = [i for i in range(100) if i%2==0]
- This is the conventional approach - here we create the full sequence of even numbers and put it in memory.
- even_numbers_generator = (i for i in range(100) if i%2==0)
- By using () instead of [] we use generators instead of tuples. Object that even_numbers_generator is pointing to is of Generator class.
- What's different? Values are not generated yet.
- Generator object will yield elements, one by one, as one explicitly or implicitly call next() on the Generator object.
- So, if I do the following:
- for number in even_numbers_generator:
- print number
- Each number will be generated in its corresponding iteration, and previously printed values won't be available again.
- if the next line would be:
- for number in even_numbers_generator:
- print number**2
- An error would be thrown - we've already iterated once using the generator object.
- To summarize: use generators instead of lists if you don't need to iterate over the sequence more than once.
- They also work great with any or all operators.
- For example:
- return any(item in items if item.boolean_attribute == True) is more elegant than:
- for item in items:
- if item.boolean_attribute:
- return True
- return False
- (generator expression could have been simplified and written without == True to make it more elegant, left it for demonstration purposes).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement