python generators medium.com

>>>def gen_squares(iterable):>>>    for each in iterable:>>>        print (f'Here comes the square of {each}')>>>        yield each*each>>>        print (f'moving on  {each}')        >>>counter = gen_squares([1,2,3,4,5]) #generator was created, but is        #idle no memory usage until next() is called inside list().>>>print(counter)    <generator object gen_squares at 0x7f2dc8aaaa00>>>>print(next(counter))    Here comes the square of 1    1>>>print(next(counter))    moving on  1    Here comes the square of 2    4>>>print(next(counter))    moving on  2    Here comes the square of 3    9>>>print(next(counter))    moving on  3    Here comes the square of 4    16>>>print(next(counter))    moving on  4    Here comes the square of 5    25>>>print(list(counter))    Traceback (most recent call last):      File "main.py", line 17, in <module>        print(next(counter))    StopIteration>>>counter2 = gen_squares([1,2,3,4,5])>>>print(next(counter2))    Here comes the square of 1    1>>>print(list(counter2))    moving on  1    Here comes the square of 2    moving on  2    Here comes the square of 3    moving on  3    Here comes the square of 4    moving on  4    Here comes the square of 5    moving on  5    [4, 9, 16, 25]

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source