Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use iterator in while loop statement in python

Is it possible to use a generator or iterator in a while loop in Python? For example, something like:

i = iter(range(10))
while next(i):
    # your code

The point of this would be to build iteration into the while loop statement, making it similar to a for loop, with the difference being that you can now additional logic into the while statement:

i = iter(range(10))
while next(i) and {some other logic}:
    # your code

It then becomes a nice for loop/while loop hybrid.

Does anyone know how to do this?

like image 578
Union find Avatar asked Nov 28 '19 15:11

Union find


People also ask

What iteration does while loop use in Python?

Python, while loop is used for performing an indefinite iteration. That means repeatedly executing a section of code until a condition is met or no longer met. Where the number of times the loop will be executed, is not specified explicitly in advance. This process will continue till the condition gets false.

How do you write a for loop in Python using iterator?

It uses the next() method for iteration. next ( __next__ in Python 3) The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object which further uses next() method to iterate over.

How do I use an iterator in Python?

Create an IteratorTo create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.

Can we iterate through set by using while loop in Python?

You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.


1 Answers

In Python >= 3.8, you can do the following, using assignment expressions:

i = iter(range(10))
while (x := next(i, None)) is not None and x < 5:
    print(x)

In Python < 3.8 you can use itertools.takewhile:

from itertools import takewhile

i = iter(range(10))
for x in takewhile({some logic}, i):
    # do stuff

"Some logic" here would be a 1-arg callable receciving whatever next(i) yields:

for x in takewhile(lambda e: 5 > e, i):
    print(x)
0
1
2
3
4
like image 98
user2390182 Avatar answered Sep 30 '22 08:09

user2390182