Python iter() — A Simple Illustrated Guide with Video

Python’s built-in iter() function returns an iterator for the given object. For example, iter([1, 2, 3]) creates an iterator for the list [1, 2, 3]. You can then iterate over all elements in the iterator, one element at a time, in a for or while loop such as: for x in iter([1, 2, 3]).

Basic Syntax iter()

Syntax: 
iter(iterable) # create an iterator that iterates over the argument iterable. 
ArgumentsiterableThe iterable over which you want to iterate.
Return ValueiteratorAn iterator that iterates over the argument iterable.

Basic Example: iter(iterable)

Learn by example! Here are some basic examples of how to use the iter() built-in function with one argument:

customers = ['Alice', 'Bob', 'Carl', 'Dave', 'Elena', 'Frank']
iterator = iter(customers)

print(next(iterator))
print(next(iterator))

for x in iterator:
    print(x)

You create an iterator over the customers list. You can either call the next() function on the resulting iterator to get the next element in the iterator. Or, you can iterate over the iterator using the for ... in ... syntax.

The output is:

Alice
Bob
Carl
Dave
Elena
Frank

Note that each time you call next(), implicitly or explicitly in a loop, the next element is consumed and will never be revisited again in this iterator. That’s why each element is printed only once.

Advanced Syntax iter()

Syntax: 
iter(callable, sentinel)    # Calls the callable until the sentinel is returned. 
Python iter() Explained - Sentinel + Callable
ArgumentscallableA function or object that can be called to retrieve the next value.
sentinelThe stop value. The callable is called until it returns the sentinel.
Return ValueiteratorAn iterator that calls the callable until the sentinel object is returned.

Advanced Example: iter(callable, sentinel)

You can create your own iterator based on nothing but a function—or another callable for that matter. Any function has a return value. By defining a so-called “sentinel” value, you can instruct the iterator to keep executing the function as long as it doesn’t return the sentinel. But if it does, the iterator wrapping the function terminates.

Here’s an example of an iterator that rolls the dice until it gets the dice value 6.

import random


# Function that returns number between 1 and 6
def roll_dice():
    return random.randint(1,6)

# Create iterator:
# ---> callable: roll_dice
# ---> sentinel: 6
my_lucky_streak_iter = iter(roll_dice, 6)


# Iterate until you roll dice value 6
for x in my_lucky_streak_iter:
    print('Dice roll', x)

# Sucess!
print('Yay! Dice roll', 6)

In an example run on my computer, I get the following output:

Dice roll 5
Dice roll 1
Dice roll 3
Dice roll 3
Dice roll 4
Dice roll 1
Dice roll 1
Dice roll 5
Dice roll 1
Dice roll 5
Dice roll 2
Dice roll 4
Dice roll 4
Dice roll 1
Dice roll 2
Dice roll 1
Dice roll 4
Dice roll 5
Yay! Dice roll 6

In another run, it gets to the value 6 much faster:

Dice roll 5
Dice roll 1
Dice roll 3
Dice roll 1
Dice roll 3
Dice roll 5
Dice roll 5
Dice roll 5
Dice roll 3
Dice roll 5
Yay! Dice roll 6

Interactive Shell Exercise: Understanding iter()’s Sentinel Value

Consider the following interactive code:

Exercise: Change the sentinel value to 3. How many times do you have to roll the dice?


But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


Summary

Python’s built-in iter() function returns an iterator for the given object. For example, iter([1, 2, 3]) creates an iterator for the list [1, 2, 3]. You can then iterate over all elements in the iterator, one element at a time, in a for or while loop such as: for x in iter([1, 2, 3]).

There are two ways of creating an iterator with iter():

  • iter(iterable) # create an iterator that iterates over the argument iterable.
  • iter(callable, sentinel) # calls the callable until the sentinel is returned.

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

References: