When traversing a list in Python using a for loop, users may encounter an unexpected inability to alter its elements without employing list comprehensions.
The crux of the issue lies in the behavior of the for i in li loop construct. Internally, it iterates as follows:
for idx in range(len(li)): i = li[idx] i = 'foo'
As seen, i is initially assigned a reference to an element in the list. Any subsequent modification to i only affects the local variable, not the list item itself.
To address this, one can either leverage list comprehensions:
li = ["foo" for i in li]
Or, traverse the indices explicitly:
for idx in range(len(li)): li[idx] = 'foo'
Alternatively, enumerate can be employed to simplify the process:
for idx, item in enumerate(li): li[idx] = 'foo'
The above is the detailed content of Why Can't I Modify a Python List Directly Within a `for` Loop?. For more information, please follow other related articles on the PHP Chinese website!