Hello friend while learning python it came into my mind that is there any way by which we can directly jump to a particular value of iterator without iterating fro example
a=range(1.10) or (1,2,3,4,5,6,7,8,9)
for i in a
print ("value of i:",i)
if (certain condition)
#this condition will make iterator to directly jump on certain value of
#loop here say if currently i=2 and after this it will directly jump the
#the iteration value of i=8 bypassing the iterations from 3 to 7 and
#saving the cycles of CPU)
There is a solution, however it involves complicating your code somewhat.
It does not require an
if function however it does require both
If you wish to change the numbers skipped then you simply change the
for _ in range() statement.
This is the code:
a = [1,2,3,4,5,6,7,8,9,10] at = iter(a) while True: try: a_next = next(at) print(a_next) if a_next == 3: for _ in range(4, 8): a_next = next(at) a_next = str(a_next) print(a_next) except StopIteration: break
The iterator interface is based on the
next method. Multiple next calls are necessary to advance in the iteration for more that one element. There is no shortcut.
If you iterate over sequences only, you may abandon the interator and write an old-fashioned C-like code that allows you to move the index:
a = [1,2,3,4,5,6,7,8,9,10] a_len = len(a) i = 0 while i < a_len: print(a[i]) if i == 2: i = 8 continue i += 1