Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't var = [0].extend(range(1,10)) work in python?

Tags:

python

list

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?

like image 627
Micah Avatar asked Jul 20 '12 21:07

Micah


4 Answers

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))
like image 121
orlp Avatar answered Oct 08 '22 02:10

orlp


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]
like image 36
Levon Avatar answered Oct 08 '22 00:10

Levon


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.

like image 4
Óscar López Avatar answered Oct 08 '22 02:10

Óscar López


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.)

like image 3
abarnert Avatar answered Oct 08 '22 02:10

abarnert