Junior — Middle
Is it possible to use an iterator directly inside a for loop in Python?
sobes.tech AI
Answer from AI
Yes, in Python, you can use an iterator directly inside a for loop. The for loop automatically calls the iterator's __next__() method on each iteration until a StopIteration exception is raised.
Example:
my_list = [1, 2, 3]
iterator = iter(my_list)
for item in iterator:
print(item)
This code will output the list elements one by one, using the iterator directly in the for loop.