Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Python Iterables | Iterators and Generators
Python Advanced Concepts
course content

Course Content

Python Advanced Concepts

Python Advanced Concepts

1. Modules and Imports
2. Error Handling
3. File Handling
4. Pytest Framework
5. Unittest Framework
6. Iterators and Generators

bookPython Iterables

What Are Iterables?

In Python, iterables are objects that can be traversed or looped over, returning their elements one by one. This ability to produce one element at a time makes them invaluable in tasks such as looping, comprehension, and unpacking.

Some common iterables include:

  • Data structures: lists, tuples, dictionaries, sets;
  • Strings: produce their characters one at a time.
  • Custom objects: made iterable by implementing the __iter__ method.

A key feature of iterables is that they do not inherently "remember" their position during traversal. To actually traverse their elements, they require an iterator.

1234567
numbers = [1, 2, 3, 4] for num in numbers: print(num) title = "codefinity" for char in title: print(char)
copy

The for loop automatically traverses the elements of the iterable and processes them one at a time.

When Python processes an iterable, it converts the object into an iterator using the iter() function. Internally, iter() calls the __iter__() method of the object. Similarly, the next() function retrieves the next value from the iterator by calling its __next__() method.

Here's an example that demonstrates how this works:

12345678910
numbers = [1, 2, 3, 4] # Converting the list to an iterator numbers_iterator = iter(numbers) # Accessing elements one at a time using `next()` print(next(numbers_iterator)) # Output: 1 print(next(numbers_iterator)) # Output: 2 print(next(numbers_iterator)) # Output: 3 print(next(numbers_iterator)) # Output: 4 print(next(numbers_iterator)) # Output: StopIteration
copy

Iterables vs. Iterators

While all iterators are iterables, not all iterables are iterators. An iterator remembers its position during traversal and provides access to elements sequentially until the end is reached.

For example:

  • Iterable: a list that can be passed to iter();
  • Iterator: the object returned by iter() that supports the next() method.

Limitation of Iterables

When working with large datasets, storing all elements in an iterable like a list can be inefficient. For instance, if the number sequence is generated dynamically or is too large to fit in memory, we need a way to process elements on demand. This is where iterators (covered in the next chapter) and lazy evaluation (introduced later) become crucial.

Task
test

Swipe to show code editor

Write a Python script to simulate rolling a shuffled six-sided die using iterators. Complete the missing parts of the code to create an iterator, retrieve elements using next(), and handle the end of iteration gracefully.

  1. A list [1, 2, 3, 4, 5, 6] represents the faces of a die. The list has already been shuffled using random.shuffle().
  2. Convert the shuffled list into an iterator so you can traverse its elements one at a time.
  3. Use the next() function to simulate rolling the die and print each face until all faces are used.
  4. When the iterator is exhausted, handle the StopIteration exception to indicate the rolls are complete.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 6. Chapter 1
toggle bottom row

bookPython Iterables

What Are Iterables?

In Python, iterables are objects that can be traversed or looped over, returning their elements one by one. This ability to produce one element at a time makes them invaluable in tasks such as looping, comprehension, and unpacking.

Some common iterables include:

  • Data structures: lists, tuples, dictionaries, sets;
  • Strings: produce their characters one at a time.
  • Custom objects: made iterable by implementing the __iter__ method.

A key feature of iterables is that they do not inherently "remember" their position during traversal. To actually traverse their elements, they require an iterator.

1234567
numbers = [1, 2, 3, 4] for num in numbers: print(num) title = "codefinity" for char in title: print(char)
copy

The for loop automatically traverses the elements of the iterable and processes them one at a time.

When Python processes an iterable, it converts the object into an iterator using the iter() function. Internally, iter() calls the __iter__() method of the object. Similarly, the next() function retrieves the next value from the iterator by calling its __next__() method.

Here's an example that demonstrates how this works:

12345678910
numbers = [1, 2, 3, 4] # Converting the list to an iterator numbers_iterator = iter(numbers) # Accessing elements one at a time using `next()` print(next(numbers_iterator)) # Output: 1 print(next(numbers_iterator)) # Output: 2 print(next(numbers_iterator)) # Output: 3 print(next(numbers_iterator)) # Output: 4 print(next(numbers_iterator)) # Output: StopIteration
copy

Iterables vs. Iterators

While all iterators are iterables, not all iterables are iterators. An iterator remembers its position during traversal and provides access to elements sequentially until the end is reached.

For example:

  • Iterable: a list that can be passed to iter();
  • Iterator: the object returned by iter() that supports the next() method.

Limitation of Iterables

When working with large datasets, storing all elements in an iterable like a list can be inefficient. For instance, if the number sequence is generated dynamically or is too large to fit in memory, we need a way to process elements on demand. This is where iterators (covered in the next chapter) and lazy evaluation (introduced later) become crucial.

Task
test

Swipe to show code editor

Write a Python script to simulate rolling a shuffled six-sided die using iterators. Complete the missing parts of the code to create an iterator, retrieve elements using next(), and handle the end of iteration gracefully.

  1. A list [1, 2, 3, 4, 5, 6] represents the faces of a die. The list has already been shuffled using random.shuffle().
  2. Convert the shuffled list into an iterator so you can traverse its elements one at a time.
  3. Use the next() function to simulate rolling the die and print each face until all faces are used.
  4. When the iterator is exhausted, handle the StopIteration exception to indicate the rolls are complete.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 6. Chapter 1
toggle bottom row

bookPython Iterables

What Are Iterables?

In Python, iterables are objects that can be traversed or looped over, returning their elements one by one. This ability to produce one element at a time makes them invaluable in tasks such as looping, comprehension, and unpacking.

Some common iterables include:

  • Data structures: lists, tuples, dictionaries, sets;
  • Strings: produce their characters one at a time.
  • Custom objects: made iterable by implementing the __iter__ method.

A key feature of iterables is that they do not inherently "remember" their position during traversal. To actually traverse their elements, they require an iterator.

1234567
numbers = [1, 2, 3, 4] for num in numbers: print(num) title = "codefinity" for char in title: print(char)
copy

The for loop automatically traverses the elements of the iterable and processes them one at a time.

When Python processes an iterable, it converts the object into an iterator using the iter() function. Internally, iter() calls the __iter__() method of the object. Similarly, the next() function retrieves the next value from the iterator by calling its __next__() method.

Here's an example that demonstrates how this works:

12345678910
numbers = [1, 2, 3, 4] # Converting the list to an iterator numbers_iterator = iter(numbers) # Accessing elements one at a time using `next()` print(next(numbers_iterator)) # Output: 1 print(next(numbers_iterator)) # Output: 2 print(next(numbers_iterator)) # Output: 3 print(next(numbers_iterator)) # Output: 4 print(next(numbers_iterator)) # Output: StopIteration
copy

Iterables vs. Iterators

While all iterators are iterables, not all iterables are iterators. An iterator remembers its position during traversal and provides access to elements sequentially until the end is reached.

For example:

  • Iterable: a list that can be passed to iter();
  • Iterator: the object returned by iter() that supports the next() method.

Limitation of Iterables

When working with large datasets, storing all elements in an iterable like a list can be inefficient. For instance, if the number sequence is generated dynamically or is too large to fit in memory, we need a way to process elements on demand. This is where iterators (covered in the next chapter) and lazy evaluation (introduced later) become crucial.

Task
test

Swipe to show code editor

Write a Python script to simulate rolling a shuffled six-sided die using iterators. Complete the missing parts of the code to create an iterator, retrieve elements using next(), and handle the end of iteration gracefully.

  1. A list [1, 2, 3, 4, 5, 6] represents the faces of a die. The list has already been shuffled using random.shuffle().
  2. Convert the shuffled list into an iterator so you can traverse its elements one at a time.
  3. Use the next() function to simulate rolling the die and print each face until all faces are used.
  4. When the iterator is exhausted, handle the StopIteration exception to indicate the rolls are complete.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

What Are Iterables?

In Python, iterables are objects that can be traversed or looped over, returning their elements one by one. This ability to produce one element at a time makes them invaluable in tasks such as looping, comprehension, and unpacking.

Some common iterables include:

  • Data structures: lists, tuples, dictionaries, sets;
  • Strings: produce their characters one at a time.
  • Custom objects: made iterable by implementing the __iter__ method.

A key feature of iterables is that they do not inherently "remember" their position during traversal. To actually traverse their elements, they require an iterator.

1234567
numbers = [1, 2, 3, 4] for num in numbers: print(num) title = "codefinity" for char in title: print(char)
copy

The for loop automatically traverses the elements of the iterable and processes them one at a time.

When Python processes an iterable, it converts the object into an iterator using the iter() function. Internally, iter() calls the __iter__() method of the object. Similarly, the next() function retrieves the next value from the iterator by calling its __next__() method.

Here's an example that demonstrates how this works:

12345678910
numbers = [1, 2, 3, 4] # Converting the list to an iterator numbers_iterator = iter(numbers) # Accessing elements one at a time using `next()` print(next(numbers_iterator)) # Output: 1 print(next(numbers_iterator)) # Output: 2 print(next(numbers_iterator)) # Output: 3 print(next(numbers_iterator)) # Output: 4 print(next(numbers_iterator)) # Output: StopIteration
copy

Iterables vs. Iterators

While all iterators are iterables, not all iterables are iterators. An iterator remembers its position during traversal and provides access to elements sequentially until the end is reached.

For example:

  • Iterable: a list that can be passed to iter();
  • Iterator: the object returned by iter() that supports the next() method.

Limitation of Iterables

When working with large datasets, storing all elements in an iterable like a list can be inefficient. For instance, if the number sequence is generated dynamically or is too large to fit in memory, we need a way to process elements on demand. This is where iterators (covered in the next chapter) and lazy evaluation (introduced later) become crucial.

Task
test

Swipe to show code editor

Write a Python script to simulate rolling a shuffled six-sided die using iterators. Complete the missing parts of the code to create an iterator, retrieve elements using next(), and handle the end of iteration gracefully.

  1. A list [1, 2, 3, 4, 5, 6] represents the faces of a die. The list has already been shuffled using random.shuffle().
  2. Convert the shuffled list into an iterator so you can traverse its elements one at a time.
  3. Use the next() function to simulate rolling the die and print each face until all faces are used.
  4. When the iterator is exhausted, handle the StopIteration exception to indicate the rolls are complete.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Section 6. Chapter 1
Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
We're sorry to hear that something went wrong. What happened?
some-alt