2

i have just confronted this situation which i am not able to understand:

In [3]: nk1=range(10) In [4]: nk2=range(11,15) In [5]: nk1.extend(nk2) In [6]: nk1 Out[6]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14] In [7]: dir(range(10))==dir(list)==dir(range(11,15))==dir(nk1)==dir(nk2) Out[7]: True In [8]: print range(10).extend(range(11,15)) None 

as you can see above that i can easily extend nk1, but why not the last statement which is returning None??
why it is returning None in In[8] input (while from In[7] we can see that all are same)???
so do i always have to make instance of range to extend it???

from python docs; i found this; but i am not getting how does above case happened.

2 Answers 2

5

When you extend a list the list is modified in-place. A new list is not returned.

In-place modifications indicate that the object whose method you're calling is going to make changes to itself during that method execution. In most cases (to avoid the confusion you're currently encountering) these types of operations do not return the object that performed the operation (though there are exceptions). Consider the following:

list1 = range(10) list2 = range(10) + range(11,15) # no in place modification here. nolist1 = list1.extend(range(11,15)) # list1 is now (0 ... 14) nolist2 = range(10).extend(range(11,15)) # Nothing actually happens here. 

In the final example, the range function returns a list which is never assigned to anything. That list is then extended, the result of which is a return value of None. This is printed.

Sign up to request clarification or add additional context in comments.

4 Comments

id(nk1) is present, also id(range(10) is also present.all of them got place. so exactly what is does IN-PLACE means???
Means, the input argument is modified, instead of returning a modified list.
@ATOzTOA so IN-PLACE means without changing its id we are changing its content??????
range() will have an id, but as it dynamically creates a list, the id is not stored anywhere unless you say x = range();. When we do extend, the value changes for the output of range() keeping the id. Also see my answer.
0

range() gives out a handle to the newly created list. If you need to modify it, you have to store the handle to a variable.

It is not printing 'None' because extend doesn't return anything. As you are using range(), there is no way to get the output directly.

nk1 = range(10) nk1.extend(range(11,15)) print nk1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.