1class RangeTen:
2 def __init__(self, *args): pass # optional
3
4 def __iter__(self):
5 '''Initialize the iterator.'''
6 self.count = -1
7 return self
8
9 def __next__(self):
10 '''Called for each iteration. Raise StopIteration when done.'''
11 if self.count < 9:
12 self.count += 1
13 return self.count
14
15 raise StopIteration
16
17for x in RangeTen():
18 print(x) # 0, 1, ..., 9
1# define a list
2my_list = [4, 7, 0, 3]
3
4# get an iterator using iter()
5my_iter = iter(my_list)
6
7# iterate through it using next()
8
9# Output: 4
10print(next(my_iter))
11
12# Output: 7
13print(next(my_iter))
14
15# next(obj) is same as obj.__next__()
16
17# Output: 0
18print(my_iter.__next__())
19
20# Output: 3
21print(my_iter.__next__())
22
23# This will raise error, no items left
24next(my_iter)
1An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
2#EXAMPLE OF ITERATOR
3nums=[2,3,4,5,6,7]
4it=iter(nums)
5print(it.__next__())
6for i in it:
7 print(i)
1class PowTwo:
2 """Class to implement an iterator
3 of powers of two"""
4
5 def __init__(self, max=0):
6 self.max = max
7
8 def __iter__(self):
9 self.n = 0
10 return self
11
12 def __next__(self):
13 if self.n <= self.max:
14 result = 2 ** self.n
15 self.n += 1
16 return result
17 else:
18 raise StopIteration
19
20
21# create an object
22numbers = PowTwo(3)
23
24# create an iterable from the object
25i = iter(numbers)
26
27# Using next to get to the next iterator element
28print(next(i))
29print(next(i))
30print(next(i))
31print(next(i))
32print(next(i))
1pies = ["cherry", "apple", "pumpkin", "pecan"]
2
3iterator = iter(pies)
4
5print(next(iterator))
6#prints "cherry" because it's the current one being iterated over
1import numpy as np
2# With array cycling
3arr = np.array([1,2,3,4,5,6,7,8,9])
4
5for i in range(len(arr)):
6 # logic with iterator use (current logic replaces even numbers with zero)
7 if arr[i] % 2 == 0: arr[i] = 0
8
9print(arr)
10# Output: [1, 0, 3, 0, 5, 0, 7, 0 , 9]
11