Created
May 27, 2015 17:18
-
-
Save heronmedeiros/adebf1a6a88c30ffa8a9 to your computer and use it in GitHub Desktop.
Using generators in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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