Last active
September 6, 2019 14:17
-
-
Save ShivamPsit/337188f3d37237f6d85bd7f32a328185 to your computer and use it in GitHub Desktop.
Generator 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
# Generators don't hold entire result in the memory instead | |
# it yields one result at a time and | |
# takes less memory and time to execute | |
def cube_num(num): | |
for i in num: | |
yield(i) | |
# Create Generator by using Comprehension : | |
# all_nums = (a*a*a for a in range(1,5)) | |
# Convert above generator to list : | |
# list(all_num) | |
all_nums = cube_num([1,2,3,4]) | |
# return generator object | |
print(all_nums) | |
# print first element | |
print(next(all_nums)) | |
# Output: | |
# <generator object cube_num at 0x02CFE470> | |
# 1 | |
# Video Tutorial : http://bit.ly/pythonGenerator | |
# Credit : Corey Schafer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment