Python Homework: Iterables and Iterators
### What are Iterables and Iterators?
- An **Iterable** is any Python object you can loop over with a for loop (like lists, tuples, strings).
- An **Iterator** is an object that remembers the current position while looping and gives the next
value when asked.
---
### Example 1: List is Iterable, not Iterator by default
```python
numbers = [1, 2, 3]
for n in numbers:
print(n)
# print(next(numbers)) # This will cause an error!
```
---
### Example 2: Converting Iterable to Iterator
```python
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it)) # 10
print(next(it)) # 20
print(next(it)) # 30
```
---
### Example 3: Generator is Iterator
```python
def countdown(n):
while n > 0:
yield n
n -= 1
cd = countdown(3)
print(next(cd)) # 3
print(next(cd)) # 2
print(next(cd)) # 1
```
---
### Homework Questions:
1. What is an iterable? Give two examples.
2. What is an iterator? How do you convert an iterable into an iterator?
3. What happens if you call `next()` on a list directly? Why?
4. Write code to create an iterator from this list: `[5, 10, 15]` and print all its items using `next()`.
5. What is a generator? Write a small generator function that yields the first 4 even numbers.
6. Explain why files in Python are considered iterators.
7. What error is raised when there are no more items left in an iterator?
---
Good luck! Practice by writing and running code yourself.