Ask Your Question

Why does .remove() seem to take every element out of a list?

asked 2019-07-20 03:56:46 +0200

sum8tion gravatar image

I've found that if I define a list

Sage: list1 = [1,2,3]

and then try to remove an element

Sage: list2 = list1.remove(2)

but then

Sage: print(list2)


edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2019-07-20 05:32:18 +0200

When you evaluate list1.remove(2), it modifies list1 and always returns None. It does not return the modified list. So:

sage: list1 = [1,2,3]
sage: list1.remove(2)
sage: list1
[1, 3]

Note that there is no output from the second line: it returns nothing. This in contrast to something like the sorted function which does not modify the original list but instead returns a new sorted list:

sage: list1 = [3,2,1]
sage: sorted(list1)
[1, 2, 3]
sage: list1
[3, 2, 1]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-07-20 03:56:46 +0200

Seen: 2,708 times

Last updated: Jul 20 '19