Iterating over a sequence and its indices simultaneously

Category: Python | posted by amaltasb

Sometimes you want to loop over a sequence but you also need to have access to the loop index. You can do this as follows:

seq = [...]
for i, value in enumerate(seq):
print "seq[%d] = %r" % (i, value)
		 
					

Collapsing a list of strings into one string

Category: Python | posted by amaltasb

If you have a list of strings like thus:

strs = ['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

and want to collapse it down to:
'The quick brown fox jumped over the lazy dog'
you can use:

' '.join(strs)