I would think that if i did the following code in python
var = [0].extend(range(1,10))
then var
would be a list with the values 0 - 9 in it.
What gives?
list.extend
is an in-place method. It performs its action on the object itself and returns None
.
This would work:
var = [0]
var.extend(range(1, 10))
Even better would be this:
var = list(range(10))
extend() doesn't return anything (actually None
), it does the change "in-place", i.e., the list itself is modified.
I think you are after this:
>>> var = [0]
>>> var.extend(range(1, 10))
>>> var
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
For the code in the question to work, you'd need to do something like this:
>>> var = [0]
>>> var.extend(range(1,10))
>>> var
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
It wasn't working before because extend() returns None
, and that's by design: Python is abiding by Command/Query Separation.
As Oscar López and others have already explained, extend is a command, which returns None, to abide by command/query separation.
They've all suggested fixing this by using extend as a command, as intended. But there's an alternative: use a query instead:
>>> var = [0] + range(1, 10)
It's important to understand the difference here. extend
modifies your [0]
, turning it into [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
. But the +
operator leaves your [0]
alone, and returns a new list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.
In cases where you've got other references to the list and want to change them all, obviously you need extend
.
However, in cases where you're just using [0] as a value, using +
not only allows you to write compact, fluid code (as you were trying to), it also avoids mutating values. This means the same code works if you're using immutable values (like tuples) instead of lists, but more importantly, it's critical to a style of functional programming that avoids side effects. (There are many reasons this style is useful, but one obvious one is that immutable objects and side-effect-free functions are inherently thread-safe.)
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