Example 1: python return iteration number of for loop
# Basic syntax:
for iteration, item in enumerate(iteratable_object):
print(iteration)
# Where:
# - item is the current element in the iteratable_object
# - iteration is the iteration number/count for the current iteration
# Basic syntax using list comprehension:
[iteration for iteration, item in enumerate(iteratable_object)]
# Example usage:
your_list = ["a", "b", "c", "d"]
for iteration,item in enumerate(your_list):
(iteration, item) # Return tuples of iteration, item
--> (0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
[iteration for iteration, item in enumerate(your_list)]
--> [0, 1, 2, 3]
Example 2: iterator in python
# define a list
my_list = [4, 7, 0, 3]
# get an iterator using iter()
my_iter = iter(my_list)
# iterate through it using next()
# Output: 4
print(next(my_iter))
# Output: 7
print(next(my_iter))
# next(obj) is same as obj.__next__()
# Output: 0
print(my_iter.__next__())
# Output: 3
print(my_iter.__next__())
# This will raise error, no items left
next(my_iter)
Example 3: 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
# create an object
numbers = PowTwo(3)
# create an iterable from the object
i = iter(numbers)
# Using next to get to the next iterator element
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
Example 4: python iterator
pies = ["cherry", "apple", "pumpkin", "pecan"]
iterator = iter(pies)
print(next(iterator))
#prints "cherry" because it's the current one being iterated over
Example 5: python for loop iterator
import numpy as np
# With array cycling
arr = np.array([1,2,3,4,5,6,7,8,9])
for i in range(len(arr)):
# logic with iterator use (current logic replaces even numbers with zero)
if arr[i] % 2 == 0: arr[i] = 0
print(arr)
# Output: [1, 0, 3, 0, 5, 0, 7, 0 , 9]