Here's a simple program:
#!/usr/bin/env python3
l = list(range(5))
print(l, type(l))
l = list(range(5)).remove(2)
print(l, type(l))
for some reason the list is destroyed on removing the element:
[0, 1, 2, 3, 4] <class 'list'>
None <class 'NoneType'>
(it is program output)
I expected it to output
[0, 1, 3, 4]
What is wrong, and how do I remove the element from a list generated with range?
You are storing the return value of the list.remove() call, not the list itself. The list.remove() call alters the list in place and returns None. It does not return the altered list.
Store the list first:
l = list(range(5))
l.remove(2)
or use a list comprehension to filter:
l = [i for i in range(5) if i != 2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With