Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

I'm following a pygame book and both of these notations appear:

for x in xs:
    # do something with x

for x in xs[:]:
    # do something with x

Do they have the same meaning?

like image 999
TheEyesHaveIt Avatar asked Jul 21 '14 02:07

TheEyesHaveIt


2 Answers

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)
like image 200
James Mills Avatar answered Nov 15 '22 03:11

James Mills


They have mostly the same meaning, except when you're modifying the list inside the body of the loop. The form list[:] explicitly makes a copy of the list before iterating over it, leaving you free to modify the original list (such as by deleting items) during loop iteration. Removing items from a list while directly iterating over it is not recommended.

like image 3
Greg Hewgill Avatar answered Nov 15 '22 04:11

Greg Hewgill