Wikipedia:Reference desk/Archives/Computing/2021 March 29

= March 29 =

What is wrong with this Python code?
Here is my code:

def remover(list): for item in list: if item > 50: list.remove(item) return(list)

number_list = [10,20,30,40,50,60,70,80,90,100] print(remover(number_list))

For my output, I get this:

[10, 20, 30, 40, 50, 70, 90]

Even though I want to get this instead:

[10, 20, 30, 40, 50]

What exactly do I need to do to fix my code in regards to this and what exactly is wrong with my code here? Futurist110 (talk) 01:24, 29 March 2021 (UTC)


 * Consider that python must use a counter to know where in the for loop it has got to. When you are processing the "60" entry, python is pointing to the sixth slot.  You delete the entry and all others move left one place, so "70" is now in the sixth slot and "80" in the seventh.  Next pass of the loop python is looking at the seventh slot, so deletes the "80", and again values shuffle down.  In the eighth pass of the loop the eighth pass of the loop "100" is in the eighth position and that too is deleted.  I don't have a solution to hand (book is elsewhere), can you reverse the order the for loop works in, "descending" or "reverse"? HTH, Martin of Sheffield (talk) 06:03, 29 March 2021 (UTC)
 * MoS nails down the issue. The best fix depends on your use case. The simplest is probably to create a new list:

def remover(l): new_list = [] for item in l:        if item <= 50: new_list.append(item) return(new_list)
 * ...which can be simplified a lot by the Pythonic magic of list comprehensions:.
 * Some stylistic comments: using list as a variable name is probably a poor idea (because list is a built-in function), and most Pythonistas would use return foo instead of return(foo) (though the latter is apparently valid syntax). Tigraan Click here to contact me 07:49, 29 March 2021 (UTC)


 * It could also be done like this:
 * --116.86.4.41 (talk) 07:54, 29 March 2021 (UTC)
 * --116.86.4.41 (talk) 07:54, 29 March 2021 (UTC)


 * You could try linting your code with a basic editor such as https://code.visualstudio.com/docs/python/linting. EpicPupper 20:42, 29 March 2021 (UTC)


 * Note, by the way, that Futurist110's code alters the input list itself – that is,

print(remover(number_list)) print(number_list)
 * will output the same thing twice – while most of the others make a new list selected from the old. —Tamfang (talk) 05:54, 4 April 2021 (UTC)