Python has several functions that can be useful when iterating over a sequence (or other iterable object). Some of these are available in the itertools module , but there are some built-in functions
that come in quite handy as well.
1)parallel iteration
Sometimes you want to iterate over two sequences at the same time.A useful tool for parallel iteration is the built-in function zip, which “zips” together the sequences, returning a list of
tuples:
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
>>> zip(names, ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
2)numbered iteration
In some cases, you want to iterate over a sequence of objects and at the same time have access to the index of the current object:
index = 0
for string in strings:
if 'xxx' in string:
strings[index] = '[censored]'
index += 1
This also seems a bit awkward, although acceptable. Another solution is to use the built-in function enumerate:
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
This function lets you iterate over index-value pairs, where the indices are supplied automatically.
3)reversed and sorted iteration
Let's look at another couple of useful functions: reversed and sorted. They're similar to the list methods reverse and sort (with sorted taking arguments similar to those taken by sort), but they
work on any sequence or iterable object, and instead of modifying the object in place, they return reversed and sorted versions:
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> reversed('Hello, world!')
<reversed object at 0xb7289fcc>
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
Note that although sorted returns a list, reversed returns a more mysterious iterable object. You don't need to worry about what this really means; you can use it in
for loops or methods such as join without any problems. You just can't index or slice it, or call list methods on it directly. In order to perform those tasks, you need to convert the
returned object, using the list type, as shown in the previous example.