try this in python shell: list.extend/append
This is what I开发者_C百科 just did in python shell:
>>>[1, 2]
...[1, 2]
>>>[1, 2].extend([2,3]) #when I pressed Enter
>>>
#nothing came out
then I tried something else:
>>>l = [1, 2]
>>>l
...[1, 2]
>>>m = [1, 2].extend([2, 3])
>>>m #pressed Enter, nothing came out
>>>m is None
...True
why? Does it mean, I cannot do something like
>>>m = [...].extend(...)
?
No you can't, extend
(as append, pop...) modify the object inplace without returning anything.
The list objects are mutable objects, they can be modified without need to recreate one.
In your case, you have to do
>>>l = [1,2]
>>>l.extend([2,3])
>>>l
[1,2,2,3]
If you change the type of l
, assume this is another object, let's call it class Foo
, what would you expect as return value of something like
foo = Foo()
foo.modify_object("here are modifications")
Won't you expect something like foo object modified, and nothing returned from the method ?
You can always do m = [...] + [...].
>>> l = [1, 2]
>>> l.extend([2, 3])
>>> l
[1, 2, 2, 3]
>>>
almost all list operations modify the list in place, e.g.
>>> m = [1, 2, 5, 6, 7, 1, 2, 4]
>>> m.sort()
>>> m
[1, 1, 2, 2, 4, 5, 6, 7]
精彩评论