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)
1>>> d = {'foo': 1, 'bar': 2, 'baz': 3}
2>>> for k, v in d.items():
3... print('k =', k, ', v =', v)
4...
5k = foo , v = 1
6k = bar , v = 2
7k = baz , v = 3
8
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