Useful Python looping techniques
26th September 2007
These are all excerpts from the Python documentation.
To synchronously and simultaneously loop over two sequences:
PYTHON:
-
questions = ['name', 'quest', 'favourite colour']
-
answers = ['Lancelot', 'the holy grail', 'blue']
-
-
for q, a in zip(questions, answers):
-
print 'What is your %s? It is %s.' % (q, a)
To loop over a sequence with both key and value:
PYTHON:
-
for i, v in enumerate(['tic', 'tac', 'toe']):
-
print i, v
To loop over dictionary, again with key and value:
PYTHON:
-
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
-
-
for k, v in knights.iteritems():
-
print k, v
To loop over some sorted sequence, but without modifying the original sequence (beware the use of set() in this example):
PYTHON:
-
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
-
-
for f in sorted(set(basket)):
-
print f











