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 ?

16th Feb 2020, 7:21 AM
Naveen K R
9 odpowiedzi
+ 3
Actually the most pythonic way would be to use a list comprehension. a = [x for x in a if x <= 4]
16th Feb 2020, 9:03 AM
Tibor Santa
Tibor Santa - avatar
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.
16th Feb 2020, 8:44 AM
Tibor Santa
Tibor Santa - avatar
0
Tibor Santa Like for i in range(len(a)) ?
16th Feb 2020, 8:47 AM
Naveen K R
0
WhyFry um which function?
16th Feb 2020, 8:48 AM
Naveen K R
0
Naveen yes...
16th Feb 2020, 9:00 AM
Tibor Santa
Tibor Santa - avatar
0
Tibor Santa can you please explain how this line of code works ?
16th Feb 2020, 9:13 AM
Naveen K R
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/
16th Feb 2020, 9:46 AM
Tibor Santa
Tibor Santa - avatar