0% found this document useful (0 votes)
6 views3 pages

Python Iterables Iterators Homework

The document explains the concepts of Iterables and Iterators in Python, highlighting that Iterables can be looped over while Iterators maintain the current position and provide the next value. It includes examples demonstrating the difference between a list (an Iterable) and an Iterator created from it, as well as a generator function. Additionally, it presents homework questions to reinforce understanding of these concepts.

Uploaded by

Pankaj Navale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Python Iterables Iterators Homework

The document explains the concepts of Iterables and Iterators in Python, highlighting that Iterables can be looped over while Iterators maintain the current position and provide the next value. It includes examples demonstrating the difference between a list (an Iterable) and an Iterator created from it, as well as a generator function. Additionally, it presents homework questions to reinforce understanding of these concepts.

Uploaded by

Pankaj Navale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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.

You might also like