Skip to content

Instantly share code, notes, and snippets.

@ShivamPsit
Last active September 6, 2019 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShivamPsit/337188f3d37237f6d85bd7f32a328185 to your computer and use it in GitHub Desktop.
Save ShivamPsit/337188f3d37237f6d85bd7f32a328185 to your computer and use it in GitHub Desktop.
Generator in Python
# 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