python copy() and remove()

Question:

I want to write copy() and remove(i) in same line, but it seems not working. However, when i separate into two lines, the answer is correct.

just curious why these two programs have different output

program 1

x = [1,2,3,4,5]
d = [1,4,5]

for i in d:
    temp = x.copy().remove(i)
    print(temp)

output:

None
None
None

program 2

x = [1,2,3,4,5]
d = [1,4,5]

for i in d:
    temp = x.copy()
    temp.remove(i)
    print(temp)

output:

[2, 3, 4, 5]
[1, 2, 3, 5]
[1, 2, 3, 4]
Asked By: huzy

||

Answers:

It is happening because the remove() operation is an in-place operation, meaning it updates the list itself and returns None, which is why you are seeing the returned value as None.

What you can do instead is use the walrus operator := to capture the result of copy(). That object would then be updated by the remove() function.

x = [1,2,3,4,5]
d = [1,4,5]

for i in d:
    (temp := x.copy()).remove(i)
    print(temp)

Output

[2, 3, 4, 5]
[1, 2, 3, 5]
[1, 2, 3, 4]
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.