Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Calling methods like pop(), insert(), and remove() on a list actually affects the contents of a list rather than returning a _copy_ of the list with everything removed. For example:

all = range(10) allbut2 = all.remove(2)

Actually removes 2 from all as well. Hence, you have to copy lists a lot if you are doing a lot of list creation or change from a master list.



list.remove() returns None. So it is a mistake to bind its return value to allbut2.

It follows the convention that methods that modify their object inplace should return None. list.pop() is an obvious exception.

You create a new list via list comprehension instead of copying and then removing:

  even = [i for i in L if i % 2 == 0] # remove odd numbers


I believe he meant:

    all = range()
    allbut2 = all
    allbut2.remove(2)
which is something that catches people all the time.


I'm totally aware of that. I'm just confused because in idiomatic Python, list copies without a map, filter, or reduce operation are very rare, so a list copy is usually replaced with a list comprehension or iterative loop of some sort.

For example, in Bravo, there are exactly eight list copies, all in contributed code which I didn't write, and another six in Exocet, which I also didn't write. The ones in Exocet are probably required, but the others are from code that was written without forethought.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: