Python
Iterator
Custom iterator implementation.
By EZ4Code Team
iteratoriterator
Code
class Range:
def __init__(self, start, end, step=1):
self.current = start
self.end = end
self.step = step
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
value = self.current
self.current += self.step
return value
for i in Range(1, 10, 2):
print(i)
# Using iter() and next()
it = iter([1, 2, 3])
print(next(it), next(it))Explanation
Implement __iter__ and __next__ methods to make an object iterable.
More Python Snippets
Sort Dictionary by Value
Sort a Python dictionary by its values in descending order.
List Comprehension
Quickly generate lists using list comprehensions.
Dictionary Merging
Multiple ways to merge dictionaries.
File Read/Write
Various ways to read and write files.
CSV Processing
Read and write CSV files using the csv module.
JSON Processing
JSON serialization and deserialization.