Xolve Xolve - 2 years ago 102
Python Question

Modifying list while iterating

l = range(100)
for i in l:
print i,
print l.pop(0),
print l.pop(0)


The above python code gives the output quite different from expected. I want to loop over items so that I can skip an item while looping.

Please explain.

Answer Source

I've been bitten before by (someone else's) "clever" code that tries to modify a list while iterating over it. I resolved that I would never do it under any circumstance.

You can use the slice operator mylist[::3] to skip across to every third item in your list.

mylist = [i for i in range(100)]
for i in mylist[::3]:
  print(i),

Other points about my example relate to new syntax in python 3.0.

  • I use a list comprehension to define mylist because it works in Python 3.0 (see below)
  • print is a function in python 3.0

Python 3.0 range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download