2

for loops in python require either iterable or iterator object.as such the following two for loops produce the same result.

list = [1,2,3,4,5,6,7,8,9]
for i in iter(list):
    print(i)
print(end = "\n")
for i in list:
    print(i)

both the for loops prints out 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 my question is why we have these two forms ? why don't we use the second form only( directly iterating over the iterable than creating iterator from it and iterating )?

Amare.m
  • 31
  • 4

2 Answers2

4

You can use iter for this type of use case

arr = [1,2,3,4,5,6,7,8,9]
  
iter_arr = iter(arr)
  
print(next(iter_arr)) # 1
print(next(iter_arr)) # 2
print(next(iter_arr)) # 3
next(iter_arr)
print(next(iter_arr)) # 5
0

iter() returns an iterable object which can be iterated one at time. Similar functionality can also be achieved by using yield keyword. This helps to reduce overhead of memory allocation.

Input:

res = [1,2,3,4,5]

Using iter():

iter_obj = iter(res)

print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))

Using Yield:

def f(res):
    for i in res:
        yield i

for i in f(res):
    print(i)

Output:

1
2
3
4
5