Junior — Middle
Explain what it means to have an object in Python that can be iterated over with a loop or the iter() function.
sobes.tech AI
Answer from AI
In Python, an object is considered iterable if it can be traversed in a for loop or if an iterator can be obtained using the iter() function. This means that the object implements the iter() method, which returns an iterator, or the getitem() method, supporting sequential access by indices.
Example of an iterable object:
my_list = [1, 2, 3]
for item in my_list:
print(item)
# You can also explicitly get an iterator
it = iter(my_list)
print(next(it)) # 1
Iterability allows convenient traversal of collection elements, such as lists, tuples, strings, and other objects that implement the corresponding protocol.