Make delicious recipes!

Iterators in Python


It is very easy to iterate over any collection in python.
Following example summarizes this:

for e in (1, 2, 3):
  print (e)

# Output:
# 1
# 2
# 3


for e in [1, 2, 3]:
  print (e)

# Output:
# 1
# 2
# 3


for key in {'key1':1, 'key2':2}:
  print (key)

# Output:
# key1
# key2


for c in "abc":
  print (c)

# Output:
# a
# b
# c


for line in open("somefile.txt"):
  print (line)


Note: The copy paste from the above may remove the indentation spaces due to which python can give indentation errors. If such a thing happens, then indentation spaces have to be put manually after copy-paste.


Generators in Python


Generators help to define custom iterators.
Beauty of generators lies in the yield statement.
yield statement can be used only within a generator and when it executes, it saves the current index of the loop and returns its argument.
When called again, the generator resumes from the state where it left off in the previous call.
On completion, generators raise the exception StopIteration which terminates the loop using the generator.


# Definition of a generator function
def myGen():
  for i in range(3,7):
    yield i

# Making use of the generator
for j in myGen():
  print (j)



Output:
3
4
5
6



Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal