Middle
Mis on iterable objekt ja kuidas sellega Pythonis töötada?
sobes.tech AI
Vastus AI-lt
In Python, an iterable object is an object that can be traversed in a for loop. It implements the __iter__() method, which returns an iterator.
An iterator is an object that implements the __next__() method, which returns the next element in the sequence and raises a StopIteration exception when the elements are exhausted.
Example:
my_list = [1, 2, 3]
# my_list is iterable
for item in my_list:
print(item)
# You can get an iterator
iterator = iter(my_list)
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
# next(iterator) will now raise StopIteration
Iterable objects are widely used for data processing, sequence generation, and in data streams in machine learning.