Whats the difference between ‘for x in list:’ and ‘for x in list[:]:’

xs[:] copies the list.

  • for x in xs — Iterate over the list xs as-is.
  • for x in xs[:] — Iterate over the a copy of list xs.

One of the reasons why you’d want to “iterate over a copy” is for in-place modification of the original list. The other common reason for “copying” is atomicity of the data you’re dealing with. (i.e: another thread/process modifies the list or data structure as you’re reading it).

Note: Be aware however that in-place modification can still modify indices of the original list you have copied.

Example:

# Remove even numbers from a list of integers.
xs = list(range(10))
for x in xs[:]:
    if x % 2 == 0:
        xs.remove(x)

Leave a Comment