## Checking if 'list' is a iterable,
# we can check if it has a '__iter__()' method using 'dir()'
# or using 'hasattr()'
print(hasattr([1, 2, 3], "__iter__")) # True
# checking for 'tuple'
print(hasattr((1, 2, 3), "__iter__")) # True
# checking if 'set' have '__iter__' method
print(hasattr({1, 2, 3}, "__iter__")) # True
## Iterables can be used in for loops
for a in (34, 32, 55, 34, 56):
print(a) # 34 32 55 34 56
## Example: Create a simple iterable object that returns multiplier
# of 10 by index
class TenMultiplier:
def __init__(self):
self.max_range = 10
# implement '__getitem__()' or '__iter__()' method to enable iteration.
# by implementing '__getitem__()' our object is also indexable
def __getitem__(self, index):
if index > self.max_range:
# 'StopIteration' is raised to break the iteration in loops
raise StopIteration
return index * 10
my_object = TenMultiplier()
# Indexing our object
print(my_object[2]) # 20
# Iterating our object
for a in my_object:
print(a) # 0 10 20 30...100