Jump to content

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

From Wikipedia, the free encyclopedia
Computing desk
< March 28 << Feb | March | Apr >> March 30 >
Welcome to the Wikipedia Computing Reference Desk Archives
The page you are currently viewing is a transcluded archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages.


March 29

[edit]

What is wrong with this Python code?

[edit]

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)[reply]

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)[reply]
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: new_list = [item for item in l if item <= 50 ].
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). TigraanClick here to contact me 07:49, 29 March 2021 (UTC)[reply]
It could also be done like this:
def remover(l):
    return list(filter(lambda x: x <= 50, l))
--116.86.4.41 (talk) 07:54, 29 March 2021 (UTC)[reply]
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)[reply]
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)[reply]