Showing posts with label Iterators part1. Show all posts
Showing posts with label Iterators part1. Show all posts

Iterators & Generators -1

Iterators

We use for statement for looping over a list.
>>> for i in [1, 2, 3, 4]:
...     print i,
...
1
2
3
4
If we use it with a string, it loops over its characters.
>>> for c in "python":
...     print c
...
p
y
t
h
o
n
If we use it with a dictionary, it loops over its keys.
>>> for k in {"x": 1, "y": 2}:
...     print k
...
y
x
If we use it with a file, it loops over lines of the file.
>>> for line in open("a.txt"):
...     print line,
...
first line
second line
So there are many types of objects which can be used with a for loop. These are called iterable objects.
There are many functions which consume these iterables.
>>> ",".join(["a", "b", "c"])
'a,b,c'
>>> ",".join({"x": 1, "y": 2})
'y,x'
>>> list("python")
['p', 'y', 't', 'h', 'o', 'n']
>>> list({"x": 1, "y": 2})
['y', 'x']