Skip to content

Instantly share code, notes, and snippets.

@heronmedeiros
Created May 27, 2015 17:18
Show Gist options
  • Save heronmedeiros/adebf1a6a88c30ffa8a9 to your computer and use it in GitHub Desktop.
Save heronmedeiros/adebf1a6a88c30ffa8a9 to your computer and use it in GitHub Desktop.
Using generators in Python
# a generator that yields items instead of returning a list
def firstn(n):
num = 0
while num < n:
yield num
num += 1
sum_of_first_n = sum(firstn(1000000))
# Build and return a list
def firstn(n):
num, nums = 0, []
while num < n:
nums.append(num)
num += 1
return nums
sum_of_first_n = sum(firstn(1000000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment