Reputation: 6957
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.
Upvotes: 2
Views: 134
Reputation: 47978
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.
Upvotes: 5
Reputation: 35950
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
Upvotes: 0