Python list! I have a question!

Asked 1 years ago, Updated 1 years ago, 371 views

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 0th position, the first 2 is cleared and defined as data = [2 1 3 2 2 2 2].
Then, when you return to forloop, 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].

python

2022-10-04 01:00

1 Answers

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}')


2022-10-04 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.