Iterator and Generators

Introduction to Iterators

  • Iterator is an object that can be iterated upon
  • Memory efficient way to iterate over large datasets
  • iter() creates an iterator; next() function gets the next value
  • Raises StopIteration error when no more items
  • Example:
    1. my_list = [1, 2, 3] my_iter = iter(my_list) print(next(my_iter)) # 1 print(next(my_iter)) # 2 print(next(my_iter)) # 3 print(next(my_iter)) # StopIteration error

Introduction to Generators

  • Function that returns an iterator and can be used in a for loop or with next()
  • Generator is a function that uses yield instead of return
  • More memory efficient than lists
  • Example:
    1. def count_up_to(n):count = 1while count <= n:yield countcount = count + 1counter = count_up_to(3) print(next(counter)) # 1 print(next(counter)) # 2 print(next(counter)) # 3 print(next(counter)) # StopIteration error
  • Note: Trying using count up to 1000000 with list and generator and see the difference

Virtual Environments

  • Used to isolate Python libraries and dependencies from another project
  • We create virtual environment, activate and install libraries in it.
  • VS-Code: Ctrl + Shift + P => Python: Create Environment => Select environment type (venv, conda, pipenv) => Select Python version => Wait for environment to be created.
  • Terminal: python -m venv env_name
  • Activate and Install Libraries
    1. Windows: env_name\Scripts\activate => pip install package_name
    2. Linux/Mac: source env_name/bin/activate => pip install package_name
  • Once environment is activated, you can see (env_name) in terminal.
  • To deactivate, run deactivate command in terminal.

AI tools

  • Install spell checker extension
  • Install black extension form microsoft and enable format on save
  • Goto VS Code extension, install and login GitHub Copilot
    1. Try generating doc-string for a function using copilot
    2. Ask copilot to generate a function to calculate factorial of a number