Skip to content

Instantly share code, notes, and snippets.

@nasturtus
Last active May 2, 2017 03:53
Show Gist options
  • Save nasturtus/8d4d95b3681b6f56b96a50a7d2432761 to your computer and use it in GitHub Desktop.
Save nasturtus/8d4d95b3681b6f56b96a50a7d2432761 to your computer and use it in GitHub Desktop.
# Generators vs List Comprehension
# References:
# 1. https://pythonprogramming.net/list-comprehension-generators-intermediate-python-tutorial/
# 2. The following is from reuven@lerner.co.il:
# That's why using a generator expression, which acts as an iterator, is often such an attractive option in Python:
# Rather than waiting for the entire thing to execute, and then returning a large list, we return the instructions
# that create a new list. In doing so, we save memory and execution time, allowing x to get something back faster.
# The fact that creating a generator expression is often just a matter of replacing the square brackets ( '[' and ']' )
# with regular parentheses ( '(' and ')' ) makes it a no-brainer in many situations.
x = (i for i in range(100)) # returns generator object, not the range of nos.
print(list(x)) # needs casting to a list in order to get the range of nos.
print()
xx = (i for i in range(100) if i % 2 == 0) # returns generator of even nos. with the exception of '0'
print(list(xx)) # needs casting to a list in order to get the range of nos.
print()
y = [i for i in range(100)] # returns ready list populated with the range of nos.
print(y)
print()
yy = [i for i in range(100) if i % 3 == 0] # returns generator of odd nos. with the exception of '0'
print(yy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment