python iterable code example
Example 1: what does iterable mean
Example 2: iterator in python
my_list = [4, 7, 0, 3]
my_iter = iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(my_iter.__next__())
print(my_iter.__next__())
next(my_iter)
Example 3: what is iterator in python
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
nums=[2,3,4,5,6,7]
it=iter(nums)
print(it.__next__())
for i in it:
print(i)
Example 4: iterator in python
class PowTwo:
"""Class to implement an iterator
of powers of two"""
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
numbers = PowTwo(3)
i = iter(numbers)
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
Example 5: interator maning
An Iterator is an object that can be used to loop through collections,
like ArrayList and HashSet. It is called an "iterator" because "iterating"
is the technical term for looping. To use an Iterator, you must import it
from the java.
Example 6: python iterator
pies = ["cherry", "apple", "pumpkin", "pecan"]
iterator = iter(pies)
print(next(iterator))