Recipe 4.4. Looping over Items and Their Indices in a SequenceCredit: Alex Martelli, Sami Hangaslammi ProblemYou need to loop on a sequence, but at each step you also need to know which index into the sequence you have reached (e.g., because you need to rebind some entries in the sequence), and Python's preferred approach to looping doesn't use the indices. SolutionThat's what built-in function enumerate is for. For example: for index, item in enumerate(sequence): if item > 23: sequence[index] = transform(item) This is cleaner, more readable, and faster than the alternative of looping over indices and accessing items by indexing: for index in range(len(sequence)): if sequence[index] > 23: sequence[index] = transform(sequence[index]) DiscussionLooping on a sequence is a very frequent need, and Python strongly encourages you to do just that, looping on the sequence directly. In other words, the Pythonic way to get each item in a sequence is to use: for item in sequence: process(item) rather than the indirect approach, typical of lower-level languages, of looping over the sequence's indices and using each index to fetch the corresponding item: for index in range(len(sequence)): process(sequence[index]) Looping directly is cleaner, more readable, faster, and more general (since you can loop on any iterable, by definition, while indexing works only on sequences, such as lists). However, sometimes you do need to know the index, as well as the corresponding item, within the loop. The most frequent reason for this need is that, in order to rebind an entry in a list, you must assign the new item to thelist[index]. To support this need, Python offers the built-in function enumerate, which takes any iterable argument and returns an iterator yielding all the pairs (two-item tuples) of the form (index, item), one pair at a time. By writing your for loop's header clause in the form: for index, item in enumerate(sequence): both the index and the item are available within the loop's body. For help remembering the order of the items in each pair enumerate yields, think of the idiom d=dict(enumerate(L)). This gives a dictionary d that's equivalent to list L, in the sense that d[i] is L[i] for any valid non-negative index i. See AlsoLibrary Reference and Python in a Nutshell section about enumerate; Chapter 19. |