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

I would think that if I did the following code in python

var = [0].extend(range(1,10)) 

then var will be a list with values ​​0 - 9 in it.

What gives?

+7
source share
4 answers

As Oscar Lopez and others have already explained, an extension is a command that returns None to perform a command / request split.

They all suggested fixing it, using the extension as a team, as intended. But there is an alternative: use the query instead:

 >>> var = [0] + range(1, 10) 

It is 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 only [0] and returns a new list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .

In cases where you have other links to the list and you want to change all of them, you obviously need to extend .

However, in cases where you simply use [0] as the value, using + not only allows you to write compact, fluid code (as you tried), but also avoids mutating values. This means that the same code works if you use immutable values ​​(like tuples) instead of lists, but more importantly, it is crucial for a functional programming style that avoids side effects. (There are many reasons why this style is useful, but one of the obvious is that immutable objects and functions without side effects are inherently thread safe.)

+3
source

list.extend is an in-place method. It performs its action on the object itself and returns None .

This will work:

 var = [0] var.extend(range(1, 10)) 

Even better:

 var = list(range(10)) 
+10
source

extend () returns nothing (actually None ), this change is "in place", i.e. list changed.

I think you are after this:

 >>> var = [0] >>> var.extend(range(1, 10)) >>> var [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
+6
source

In order for the code in the question to work, you 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 has not worked before because extend () returns None , and that by design: Python does Command / Request Separation .

+4
source

All Articles