Sobes.tech
Middle

What is an iterable object and how to work with it in Python?

sobes.tech AI

Answer from AI

An Iterable object in Python is an object that can be looped over 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) now will raise StopIteration

Iterable objects are widely used for data processing, sequence generation, and in data streams in machine learning.