Assignment changes what a variable refers to. That’s all it does.
To assign to a new value, you have to separately create that value first.
everything in python is by reference. The actual storage is somewhere else, inaccessible. Values are removed when they are no longer referred to.
But even if assignment did make a copy, which it doesn’t, your code is using the same variable when iterating and modifying, so it’s doubly wrong
And, since your code makes no operations on your newnums variable, you’ve already shown that assignment doesn’t do a copy because if a copy was made and you made no modifications to that copy, then you’d be returning a value identical to the input
Another thing is that list.remove isn’t suitable for removing multiple values because that involves a lot of moving (you need to know what things actually do when you use them)
The only suitable solution is to create a new list with the values to keep.
One could alternatively keep two locations, one where you read and one where you write, so you’d write the values back into the same list. This would be in-place, and it’s something you might see in a language like C, but it makes no meaningful difference in python, and if you cared about it then 1) it’s hard to say whether it’s faster or slower 2) you’re using the wrong language
# this is arguably not python at all
read = write = 0
stop = len(items)
while read != stop:
item = items[read]
read += 1
if item % 2 == 1:
items[write] = item
write += 1
# resize the list, eliminating junk left past what was written
data = list(range(10))
And even in languages you would do this, it’s probably mostly because of the limitations of that language, where it’s difficult to allocate new memory and to give ownership of that memory to the caller of the function - so instead the caller has to send in a piece of memory to write in.
In python that ownership is held by python itself, the programmer doesn’t need to care. And, the list doesn’t contain the values anyway, it’s all just references. Python is very far removed from needing to write code this way.
But at least it does touch on something rather important when learning to program. Python’s actions do a lot, they are wide brushes, they behave very nicely. Learners sometimes make bad assumptions about how things behave. There’s no way to do that when the programmer is painstakingly pushing every single byte around.
For example, the remove method of list causes elements to move. A beginner might not stop and think about what removing does to a list. If they had to do the removing themselves, they would know exactly what it did.