Useful Python looping techniques
26th September 2007
These are all excerpts from the Python documentation.
To synchronously and simultaneously loop over two sequences:
- 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:
- for i, v in enumerate(['tic', 'tac', 'toe']):
- print i, v
To loop over dictionary, again with key and value:
- 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):
- basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
- for f in sorted(set(basket)):
- print f
For looping sorted dictionaries, see also How to sort Python dict (dictionary).