Advertisement
Guest User

Python Generators

a guest
Jun 26th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. When people use collections of any kind in Python, most of the people rely on lists
  2. That's fine, but can we use something better than lists?
  3. Generators are a pretty nice feature of Python.
  4. 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.
  5. This can be very helpful in a memory constrained environment.
  6. So, simple example:
  7.  
  8. even_numbers = [i for i in range(100) if i%2==0]
  9.  
  10. This is the conventional approach - here we create the full sequence of even numbers and put it in memory.
  11.  
  12. even_numbers_generator = (i for i in range(100) if i%2==0)
  13.  
  14. By using () instead of [] we use generators instead of tuples. Object that even_numbers_generator is pointing to is of Generator class.
  15. What's different? Values are not generated yet.
  16. Generator object will yield elements, one by one, as one explicitly or implicitly call next() on the Generator object.
  17. So, if I do the following:
  18.  
  19. for number in even_numbers_generator:
  20. print number
  21.  
  22. Each number will be generated in its corresponding iteration, and previously printed values won't be available again.
  23. if the next line would be:
  24.  
  25. for number in even_numbers_generator:
  26. print number**2
  27.  
  28. An error would be thrown - we've already iterated once using the generator object.
  29. To summarize: use generators instead of lists if you don't need to iterate over the sequence more than once.
  30. They also work great with any or all operators.
  31. For example:
  32. return any(item in items if item.boolean_attribute == True) is more elegant than:
  33.  
  34. for item in items:
  35. if item.boolean_attribute:
  36. return True
  37. return False
  38.  
  39. (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