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
StopIterationerror when no more items my_list = [1, 2, 3] my_iter = iter(my_list) print(next(my_iter))# 1print(next(my_iter))# 2print(next(my_iter))# 3print(next(my_iter))# StopIteration error
Example:
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
yieldinstead ofreturn - More memory efficient than lists
def count_up_to(n):count = 1while count <= n:yield countcount = count + 1counter = count_up_to(3)print(next(counter))# 1print(next(counter))# 2print(next(counter))# 3print(next(counter))# StopIteration error- Note: Trying using count up to 1000000 with list and generator and see the difference
Example:
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 - Windows:
env_name\Scripts\activate=>pip install package_name - 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
deactivatecommand in terminal.
Activate and Install Libraries
AI tools
- Install
spell checkerextension - Install
blackextension form microsoft and enable format on save - Try generating doc-string for a function using copilot
- Ask copilot to generate a function to calculate factorial of a number
Goto VS Code extension, install and login
GitHub Copilot