Appending a list to itself in Python

2019-02-14 20:02发布

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 all I get back is the builtin None. What am I doing wrong? I'm using Python v2.6

5条回答
小情绪 Triste *
2楼-- · 2019-02-14 20:23

x.extend(x) will extend x inplace.

>>> print x

[1, 2, 1, 2]
查看更多
迷人小祖宗
3楼-- · 2019-02-14 20:31

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

查看更多
来,给爷笑一个
4楼-- · 2019-02-14 20:34

or just:

x = [1,2]
y = x * 2
print y
查看更多
smile是对你的礼貌
5楼-- · 2019-02-14 20:36

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

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

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-02-14 20:36

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.

查看更多
登录 后发表回答