0
Please explain why not removing all all element from l1 and explain iteration
l1=eval(input("enter list")) #l1=[10,20,30] l2=eval(input("enter list2")) #l2=[10,40,30,20,50] for x in l1: if x in l2: l1.remove(x) print(l1)
3 RĂ©ponses
+ 2
There is a similar question on Stack overflow: https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it
Briefly, how Python iterates the list is by using an internal counter starting from 0, each iteration it increased by one. The counter is used to access an item of the list. If the counter is 0, x is l1[0]. If it is 1, x is l1[1] and so on.
Go back to your question. Let's break down the code with the logic above in mind.
#1 iter l1 is [10, 20, 30]. Counter: 0
x is l1[0], in this case is 10.
10 is in l2. Remove 10 in l1.
#2 iter l1 is [20, 30]. Counter: 1
x is l1[1], in this case 30.
30 is in l2. Remove 30 in l1.
Iteration ends.
Best practice is don't modify the actual list or anything you're iterating to avoid the confusion. To safely modify the list during iteration, you should make a copy and iterate it.
+ 1
Irshad Ahmad,
At least use the tags to specify a language name (Python). Tags play an important role in post discoverability cause words in tags are search terms as per the forum's search engine ...
https://code.sololearn.com/W3uiji9X28C1/?ref=app
+ 1
you only went through the list once.
do the for loop several times using range(len())
Self mutation is tricky and should be avoided, though.
#l1=eval(input("enter list"))
l1=[10,20,30]
#l2=eval(input("enter list2"))
l2=[10,40,30,20,50]
for _ in range(len(l1)):
for x in l1:
if x in l2:
l1.remove(x)
print(l1)
print(l1)