0
Q:

iterator in python

class RangeTen:
  def __init__(self, *args): pass # optional
  
  def __iter__(self):
    '''Initialize the iterator.'''
    self.count = -1
    return self
  
  def __next__(self):
  	'''Called for each iteration. Raise StopIteration when done.'''
    if self.count < 9:
      self.count += 1
      return self.count

    raise StopIteration
    
for x in RangeTen():
  print(x) # 0, 1, ..., 9
2
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
#EXAMPLE OF ITERATOR
nums=[2,3,4,5,6,7]
it=iter(nums)
print(it.__next__())
for i in it:
  print(i)
0
pies = ["cherry", "apple", "pumpkin", "pecan"]

iterator = iter(pies)

print(next(iterator))
#prints "cherry" because it's the current one being iterated over
0
# 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)
0
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))
0

  import json

# some JSON:
x =  '{ "name":"John", "age":30, "city":"New 
  York"}'

# parse x:
y = json.loads(x)

# the result is a 
  Python dictionary:
print(y["age"]) 
3

New to Communities?

Join the community