What is the difference between "for x in the list:" and "for x in the list [:]: '

I follow the 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?

+4
source share
2 answers

xs[:] copies the list.

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

One of the reasons you want to "iterate over a copy" is to change the original list in place. Another common reason for β€œcopying” is the atomicity of the data you are dealing with. (i.e. another thread / process changes the structure of the list or data when you read it).

. , , - , .

:

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

, , . list[:] , (, ) . .

+3

All Articles