How to use while(i = getNext()) pattern in python

  • A+
Category:Languages

In C++, I often use the following pattern:

while (int i = getNextElementPlease()) {     printf("%d/n", i); } 

But in python I have to repeat call twice:

i = getNextElementPlease() while (i):     print(i)     i = getNextElementPlease() 

How to avoid duplication of getNextElementPlease?

 


Either with the classic while True/break pattern:

while True:     i = getNextElementPlease()     if not i:         break     ... 

or by using the two-argument form of iter to build an iterator out of your function:

for i in iter(getNextElementPlease, sentinel):     ... 

where sentinel is whatever value you're expecting to terminate the loop. Probably something like None. The iterator will call getNextElementPlease to get elements and stop when getNextElementPlease returns the sentinel value.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: