Using the range function with a list

To iterate over the index numbers of a sequence (such as a list), use a for statement with range() and len() (which finds the number of elements in a sequence), like this:

for i in range(len(list name)):

The enumerate() function, new in Python 2.3, works similarly. See the "Numbered and approved" section, later in this chapter, to find out more.

Warning It isn't safe to modify the list you're iterating over! To duplicate selected items or otherwise modify items in a list you're using in a loop, either

• Create a new list to store the modifications, as shown in this example:

• >>> man from st ives = ['wives', 'sacks', 'cats', 'kits']

• ['7', 'wives', '7', 'sacks', '7', 'cats', '7', 'kits']

Was this article helpful?

0 0

Post a comment