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?
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) # []
886 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
577 PHP ssh2_scp_send fails to send files as intended
599 GDB gets version error when attempting to debug with the Presense SDK (IDE)
567 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.