Frequently used python for loop examples.
For loop to iterate over a list
Iterate on each element of a list
a = ["v1", "v2", "v3"] for val in a: print val
v1 v2 v3
Env: Python 2.7.18
Iterate on each index, element of a list
a = ["v1", "v2", "v3"] for i,val in enumerate(a): print str(i) + " " + str(val)
0 v1 1 v2 2 v3
Env: Python 2.7.18
For loop to iterate over a string characters
s = "Hello" for val in s: print val
H e l l o
Env: Python 2.7.18
For loop to iterate over a dictionary
Iterate over dictionary keys, values or both
d = {"k1":"v1", "k2":"v2", "k3":"v3"} ## or d.keys() for key in d: print key for val in d.values(): print val for key,val in d.items(): print key, val
k3 k2 k1 v3 v2 v1 k3 v3 k2 v2 k1 v1
Env: Python 2.7.18
For loop to iterate over a dictionary using iterators
Iterate over dictionary keys, values or both using iterators. This does not create a new copy and may be little more memory efficient for large dictionaries.
d = {"k1":"v1", "k2":"v2", "k3":"v3"} for key in d.iterkeys(): print key for val in d.itervalues(): print val for key,val in d.iteritems(): print key, val
k3 k2 k1 v3 v2 v1 k3 v3 k2 v2 k1 v1
Env: Python 2.7.18