Python extend with an empty list bug?

Question:

Why does python 2.5.2 have the following behavior

>>>[2].extend([]) == [2]
False

>>> [2].extend([]) == None
True

$ python --version
Python 2.5.2

I assume I’m not understanding something here, but intuitively I’d think that [2].extend([]) should yield [2]

Asked By: Doug T.

||

Answers:

Extend is a method of list, which modifies it but doesn’t return self (returning None instead). If you need the modified value as the expression value, use +, as in [2]+[].

Answered By: RafaƂ Dowgird

Exactly.

>>> x = [2]
>>> x.extend([]) # Nothing is printed because the return value is None
>>> x == [2]
True
>>> x
[2]

They do this on purpose so that you will remember that the extend function is actually modifying the list in-place. Same with sort(). It always returns None.

Answered By: Tyler
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.