+ 3
Does remove() method of list affect iteratin of lops and if how
Hey check this code in this the loop is iterating less then it should when I apply <list>.remove () method but when I don't use <list>.remove () it iterates all values. So does <list>.remove () some how affect the iterations of list https://code.sololearn.com/c4i6v5C2cWXf/?ref=app SOLVED
7 Respuestas
+ 1
Yes, it does, you can instead do:
for i in mylist[:] :
mylist.remove(i)
_______________
Please check the modified version of your code here: https://code.sololearn.com/cgghYpkA0pU0/?ref=app
________________
Also, I have added a better way to parse the list than eval()
________________
The case here is that when you iterate over a list , the for loop gets mylist[0]
then remove it from mylist, then next loop round it tries to get mylist[1], which is now the item that was mylist[2] before, and the original mylist[1] is now the new mylist[0], which will not be removed at all now.
tldr;
Your code will miss the next item after each time it removes.
let me know if it needs clarification
+ 2
Hey I think both of you are not able to understand the question it is talking about lists and I have already attached the code
+ 2
Hey I don't have any problem in My code but I want to ask if remove() some how affects iteration of loop as in presence of remove () every element is only once iterated but not in presence of remove ()
+ 1
b=str(eval(input("Enter a list of number:")))
print()
d=list(b)
b=list(b)
print("actual list",b)
print()
print("with remove")
for a in b:
b.remove(a)
print(a)
print()
print("without remove")
for a in d:
print(a)
+ 1
That's your code fixed or at least it will run when given a proper input.
+ 1
Your code doesn't run without error in its current state.
eval() returns a number which will cause an error when you try to convert b to list d. Then in your first for loop you're treating b as if it is a list when it is a number again more errors. So, yes, your code and/ or your logic has problems.
But to answer your question yes it will effect iteration, because of the way your changing the length of the list that you're also looping on at the same time.
0
👋
In python the strings are immutable, that's why they don't have a function to remove elements unlike lists