import random
data=[random.randint(1,3) for i in range(10)]
print(data)
target=2
print(f'target({target}) before deletion:{data}')
for n in data:
if n==target:
data.remove(target)
print(f'target({target}) after deletion:{data}')
I have a question in this code.
First of all, there is [2 2 1 3 2 2 2 2]
in the list
Since for
is executed in the 0
th position, the first 2
is cleared and defined as data = [2 1 3 2 2 2 2]
.
Then, when you return to for
loop, since you run it at the first position, doesn't the element in index 1 clear and become data = [2 3 3 1 2 2]
?
I don't understand why the execution result is [1,3,3,1,2,2]
.
It's simple. where n
is not an index, but a value assigned to that index. In the given example, [2, 2, 1, 3...]
After this first tour [2, 1, 3...]The reason why it became
was not because it was n=0
during the first tour, but because the first data I checked was 2
. It's a pure coincidence.
If you're not sure, take a lot of print()
.
import random
data = [random.randint(1,3) for i in range(10)]
print(data)
target = 2
print(f'target({target}) before deletion:{data}')
for n in data:
log = str(n)
if n == target:
log += ' ---> should eliminate!'
data.remove(target)
print(log)
print(f'target({target}) after deletion:{data}')
© 2025 OneMinuteCode. All rights reserved.