0
For loop working in Python
I wrote the following code to delete the numbers which is greater than 4 from a sorted list. a="1 2 3 4 5 6 7 8 9" a=a.split() for i in a : if int(i) > 4: del a[a.index(i)] print(a) What I expected was ["1","2","3","4"] But what I got was ["1","2","3","4","6","8"] Can someone tell me why is this ?
7 Réponses
+ 3
Actually the most pythonic way would be to use a list comprehension.
a = [x for x in a if x <= 4]
0
In fact it is a very bad practice to mutate a list while you are looping through it. Precisely because it is difficult to debug, and could lead to unexpected errors. Better to loop through a range that represents the list indices.
0
Tibor Santa Like for i in range(len(a)) ?
0
WhyFry um which function?
0
Naveen yes...
0
Tibor Santa can you please explain how this line of code works ?
0
It creates a new list from the elements of 'a' which are not greater than 0.
List comprehensions are explained in the SL lessons, if you haven't learned them yet then just keep moving on until you get there :)
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2454/