开发者

Appending a list to itself in Python [duplicate]

This question already has answers here: Why do these list methods (append, sort, extend, remove, clear, reverse) return None rather than the resulting list? (6 answers) Closed 6 months ago.

I want to attach a list to itself and I thought this would work:

x = [1,2]
y = x.extend(x)
print y

I wanted to get back [1,2,1,2] but a开发者_如何学运维ll I get back is the builtin None. What am I doing wrong? I'm using Python v2.6


x.extend(x) does not return a new copy, it modifies the list itself.

Just print x instead.

You can also go with x + x


x.extend(x) modifies x in-place.

If you want a new, different list, use y = x + x.


or just:

x = [1,2]
y = x * 2
print y


x.extend(x) will extend x inplace.

>>> print x

[1, 2, 1, 2]


If you want a new copy of the list try:

x = [1,2]
y = x + x
print y # prints [1,2,1,2]

The difference is that extend modifies the list "in place", meaning it will always return None even though the list is modified.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜