Autarchy of the Private Cave

Tiny bits of bioinformatics, [web-]programming etc

    Useful Python looping techniques

    26th September 2007

    These are all excerpts from the Python documentation.

    To synchronously and simultaneously loop over two sequences:

    1. questions = ['name', 'quest', 'favourite colour']
    2. answers = ['Lancelot', 'the holy grail', 'blue']
    3.  
    4. for q, a in zip(questions, answers):
    5.     print 'What is your %s?  It is %s.' % (q, a)

    To loop over a sequence with both key and value:

    1. for i, v in enumerate(['tic', 'tac', 'toe']):
    2.     print i, v

    To loop over dictionary, again with key and value:

    1. knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    2.  
    3. for k, v in knights.iteritems():
    4.     print k, v

    To loop over some sorted sequence, but without modifying the original sequence (beware the use of set() in this example):

    1. basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
    2.  
    3. for f in sorted(set(basket)):
    4.     print f

    For looping sorted dictionaries, see also How to sort Python dict (dictionary).

    Share

    Leave a Reply

    XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>