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.
Arguments | iterable | The iterable over which you want to iterate. |
Return Value | iterator | An 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.
Arguments | callable | A function or object that can be called to retrieve the next value. |
sentinel | The stop value. The callable is called until it returns the sentinel. | |
Return Value | iterator | An 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?
Check out 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).
Publisher 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!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
References:
- https://docs.python.org/3/library/functions.html#enumerate
- https://book.pythontips.com/en/latest/enumerate.html
- https://realpython.com/python-enumerate/
- https://www.geeksforgeeks.org/enumerate-in-python/
- https://www.programiz.com/python-programming/methods/built-in/enumerate
- https://www.w3schools.com/python/ref_func_enumerate.asp
- https://www.afternerd.com/blog/python-enumerate/
- https://careerkarma.com/blog/python-enumerate/