Iterator and Generators
✕1. 🔁 Iterators
- Imagine watching videos in a playlist. When you press Next, the playlist gives the next video. It does not show all videos at once. It gives one video at a time. An iterator works in a similar way.
An iterator is an object that gives values one at a time when we call
next(). Iterators are useful when we want to go through items one by one. They are also useful for working with large data because they do not need to give all values at once. Example:my_list = [1, 2, 3]my_iter = iter(my_list)print(next(my_iter))# ➜ 1print(next(my_iter))# ➜ 2print(next(my_iter))# ➜ 3 iter()is used to create an iterator.next()is used to get the next value from an iterator. Example:numbers = [10, 20, 30]number_iterator = iter(numbers)print(next(number_iterator))# ➜ 10print(next(number_iterator))# ➜ 20print(next(number_iterator))# ➜ 30 📌 Eachnext()call gives the next item. 📌 The iterator remembers where it stopped.- When there are no more items left, Python raises StopIteration.
Example:
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 ⚠️ StopIteration means there are no more values left in the iterator. - A
forloop can use an iterator automatically. Example:my_list = [1, 2, 3]for item in my_list:print(item)Output: 1 2 3 📌 Internally, aforloop gets values one by one. 📌 We usually useforloops because they are easier than callingnext()again and again.
1.1 What is an Iterator?
1.2 iter() and next()
1.3 StopIteration
1.4 Iterator with for Loop
2. ⚙️ Generators
- Imagine a token machine. It gives one token only when someone asks for it. It does not print all tokens at once. A generator works in a similar way.
A generator gives values one by one only when needed. A generator is a special function that uses
yieldinstead ofreturn. It returns a generator object, which can be used withnext()or aforloop. 📌 Generators are memory efficient because they produce values one at a time. yieldis used to give one value from a generator. Unlikereturn,yielddoes not completely end the function. It pauses the function and remembers where it stopped. Whennext()is called again, the generator continues from the same place. Example: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))# ➜ 3- When a generator has no more values, Python raises StopIteration.
Example:
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 - A generator can also be used directly in a
forloop. Example:def count_up_to(n):count = 1while count <= n:yield countcount = count + 1for num in count_up_to(3):print(num)Output: 1 2 3 📌forloop automatically handles StopIteration. - A list stores all values in memory. A generator creates values only when needed.
Example using list:
numbers = [1, 2, 3, 4, 5]Example using generator:def generate_numbers():for num in range(1, 6):yield num📌 For small data, lists are fine. 📌 For very large data, generators can save memory. Try this: Create numbers up to 1000000 using a list. Then create numbers up to 1000000 using a generator. Observe the difference.
2.1 What is a Generator?
2.2 yield Keyword
2.3 Generator and StopIteration
2.4 Generator with for Loop
2.5 Why Generators are Memory Efficient
3. ⚖️ Iterator vs Generator
- Both
- Both iterators and generators give values one at a time.
- Both remember their current position.
- Both can be used with:
next(),forloop - Both can raise StopIteration when no more values are left. - Iterator:
- Created using
iter()- Can be made from lists, tuples, strings, etc. Generator: - Created using a function withyield- Useful when values should be generated only when needed Example of iterator:numbers = [1, 2, 3]my_iter = iter(numbers)print(next(my_iter))# ➜ 1 Example of generator:def generate_numbers():yield 1yield 2yield 3gen = generate_numbers()print(next(gen))# ➜ 1 - Use a generator when: ✅ We want values one by one ✅ We do not want to store all values at once ✅ We are working with large data ✅ We want memory-efficient code
3.1 Similarity
3.2 Difference
3.3 When to Use Generator
4. 🧰 Virtual Environments
- Imagine you have two games on your computer. One game works properly only with an older version of a game plugin. Another game needs the latest version of the same plugin. If both games are forced to use one shared plugin version, one game may stop working properly. So each game needs its own separate setup. A virtual environment works in a similar way. A virtual environment keeps one project's Python libraries separate from another project's libraries. This helps avoid package conflicts. Example: Project A may need one version of a library. Project B may need a different version of the same library. Using separate virtual environments prevents conflict.
- Virtual environments help us: ✅ Keep project libraries separate ✅ Avoid package version conflicts ✅ Install only the libraries needed for one project ✅ Make projects easier to manage ✅ Work safely without affecting other projects
- Using terminal:
python -m venv .venvHere:python➜ Runs Python-m venv➜ Uses Python's venv module.venv➜ Name of the virtual environment folder 📌.venvis a common name for virtual environment folders. - For Windows:
.venv\Scripts\activateFor Mac/Linux:source .venv/bin/activateAfter activation, you may see this in the terminal:(.venv)This means the virtual environment is active. - After activating the virtual environment, install libraries using pip.
Example:
pip install requestsAnother example:pip install pandas📌 Libraries installed here belong to this project environment. - To deactivate the virtual environment, run:
deactivateAfter deactivation, the terminal returns to the normal Python environment. - In VS Code, we can also create a virtual environment using the Command Palette.
Steps:
1. Open VS Code.
2. Open your project folder.
3. Press
Ctrl + Shift + P. 4. SearchPython: Create Environment. 5. Choose environment type such as venv. 6. Select Python version. 7. Wait for the environment to be created. 📌 VS Code can help create and manage Python environments from the editor.
4.1 What is a Virtual Environment?
4.2 Why Use Virtual Environments?
4.3 Creating a Virtual Environment
4.4 Activating Virtual Environment
4.5 Installing Libraries
4.6 Deactivating Virtual Environment
4.7 Creating Environment in VS Code
5. 🧑💻 VS Code and AI Coding Tools
- Some useful VS Code tools are: - Python extension - Spell checker extension - Black formatter - GitHub Copilot, installed by default These tools help us write, format, and improve code more easily.
- A spell checker helps find spelling mistakes in comments, documentation, and text. Example: Wrong: This funcion calculate area. Correct: This function calculates area.
- Black is a Python code formatter. It helps format Python code consistently.
Example:
Before formatting:
def add(a,b): return a+bAfter formatting:def add(a, b):return a + b📌 Formatting makes code easier to read. - GitHub Copilot is an AI coding assistant. It can help suggest code, explain code, and generate code examples. In VS Code: 1. Open GitHub Copilot. 2. Sign in with your GitHub account. 3. Open a code file. 4. Start typing or ask Copilot for help. For detail step by step guide with video, refer How to Create and Configure GitHub Account.Example tasks: - Generate a docstring for a function - Generate a function to calculate factorial - Explain a block of code - Suggest improvements to code 📌 Always review AI-generated code before using it. 📌 AI tools can make mistakes, so we should understand and test the code.
5.1 Useful VS Code Extensions
5.2 Spell Checker
5.3 Black Formatter
5.4 GitHub Copilot
Practice QuestionsNot started
1. Iterator Basics
Question 1 of 5
- Create a list
numbers = [10, 20, 30]. Create an iterator from this list usingiter(). Usenext()to print each value one by one. - Create a string
word = "Python". Create an iterator from this string and print each character usingnext(). - Create a tuple
colors = ("red", "green", "blue"). Useiter()andnext()to print all values. - Try calling
next()after all values are finished and observe StopIteration.
1.1 Practice iterator basics:- Create a list
2. Generator Basics
Question 2 of 5
- Write a generator function
count_up_to(n)that gives numbers from 1 to n. - Use
next()to print values fromcount_up_to(5). - Use a
forloop to print values fromcount_up_to(5). - Write a generator function
even_numbers(n)that gives even numbers from 1 to n. - Write a generator function
square_numbers(n)that gives squares from 1 to n.
2.1 Practice generator basics:- Write a generator function
3. Iterator and Generator Practice
Question 3 of 5
- Create a generator that gives first 10 multiples of 5.
- Create a generator that gives characters from a string one by one.
- Create a generator that gives numbers in reverse from n to 1.
- Compare list and generator by creating numbers from 1 to 1000000. Observe which one stores all values and which one generates values one by one.
3.1 Practice combined iterator and generator tasks:4. Virtual Environment Practice
Question 4 of 5
- Create a new project folder.
- Open the folder in VS Code.
- Create a virtual environment using:
python -m venv .venv - Activate the virtual environment.
- Install one package using pip. Example:
pip install requests - Deactivate the virtual environment.
4.1 Practice creating and using a virtual environment:5. Personal Portfolio Project
Question 5 of 5
- Create a new folder for your personal portfolio project.
- Using GitHub Copilot, create a simple personal portfolio website. The website should include: - Your image - Short bio - List of projects - Skills - Contact information. For sample prompt and video, refer How to Create a Personal Website without Coding
- Review the generated code and ask Copilot to make the changes you want.
- Register a domain name from register website to host your portfolio later. Detail video with step by step guide at: How to host a Website for Free.
5.1 Practice building your personal portfolio:
