counter loops: range(-5,3)
len(list)
parallel traversals: zip and map
L1=[1,2,3,4]
L2 = [5,6,7,8]
zip(L1, L2)
[(1, 5), (2, 6), (3, 7), (4, 8)]
for (x,y) in zip(L1,L2):
print x, y, '--', x+y
zip truncates result tuples at the length of the shortest sequence when the
argument lengths differ.
>>> S1 = 'abc'
>>> S2 = 'xyz123'
>>> map(None, S1, S2) # 2.X only: pads to len(longest)
[('a', 'x'), ('b', 'y'), ('c', 'z'), (None, '1'), (None, '2'), (None,'3')]
>>> list(map(ord, 'spam'))
[115, 112, 97, 109]
works the same as
This works the same as the following loop statement, but map is often quicker:
>>> res = []
>>> for c in 'spam': res.append(ord(c))
>>> res
[115, 112, 97, 109]
>>> keys = ['spam', 'eggs', 'toast']
>>> vals = [1, 3, 5]
>>> D = {}
>>> for (k, v) in zip(keys, vals): D[k] = v
>>> S = 'spam'
>>> for (offset, item) in enumerate(S):
... print(item, 'appears at offset', offset)
...
s appears at offset 0
p appears at offset 1
a appears at offset 2
m appears at offset 3
>>> E = enumerate(S)
>>> E
<enumerate object at 0x0000000002A8B900>
>>> next(E)
(0, 's')
>>> next(E)
(1, 'p')
>>> next(E)
(2, 'a')