Python for Moon

Asked 2 years ago, Updated 2 years ago, 67 views

a = ['123']

b = ['345', '456', '675', '678']

for i in b:
    if i not in a:
        b.remove(i)

print(b)

The desired result value of b is [], but why is only the first element deleted?

for

2022-09-22 18:48

1 Answers

This is because the list being circulated is the same as the list being remove().

a = ['123']
b = ['345', '456', '675', '678']
for i in b:
    print("Now i -->", i)
    if i not in a:
        print("not yet b -->", b)
        b.remove(i)
        print("Now b -->", b)

If you run the code above, you'll see this.

Now i --> 345
Not yet b --> ["345", "456", "675", "678"]
Now b --> ["456", "675", "678"]
Now i --> 675
Not yet b --> ["456", "675", "678"]
Now b --> ["456", "678"]

If you look at the second "i" now, I think '456' should come out, but I'm taking out '675'. Because what Python thinks about b is that the index that we have to go around this time is 1. The element corresponding to index number 1 of ['456', '675', '678'] will be '675', so you will select and clear '675' here.

First of all, the shortest and fastest way to get what you want is to go around the original copy of .

fori in list(b): #<-- You can get what you want just by changing it like this

To approach the problem more semantically, this task is essentially to filter out only certain elements from a specific list, so these approaches are possible.

a = ['123']
b = ['345', '456', '675', '678']
c = list(filter(lambda x: x in a, b))
d = [x for x in b if x in a]
print(c) # []
print(d) # []


2022-09-22 18:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.