Wednesday, April 2, 2014

list update

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

for w in words[:]:  # Loop over a slice copy of the entire list.
    if len(w) > 6:
        words.insert(0, w)

#words: ['defenestrate', 'cat', 'window', 'defenestrate']

No comments:

Post a Comment