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?
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With