7

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

joaquin
  • 82,968
  • 29
  • 138
  • 152
Double AA
  • 5,759
  • 16
  • 44
  • 56

5 Answers5

12

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

Stefan Kanev
  • 3,030
  • 22
  • 17
2

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

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

Amber
  • 507,862
  • 82
  • 626
  • 550
1

or just:

x = [1,2]
y = x * 2
print y
fransua
  • 1,559
  • 13
  • 30
  • You are creating `[x, x]`, if one element of `x` changes, it will change in the other index of `y`, too: http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly – Schorsch Nov 08 '16 at 17:58
  • 2
    @Schorsch That is true for `[x] * 2` which is equivalent to `[x] + [x]`. However, `x * 2` is equivalent to `x + x` which creates a "shallow" list of values in this case. – Shmuel Valariola Jun 11 '20 at 00:47
0

x.extend(x) will extend x inplace.

>>> print x

[1, 2, 1, 2]
Dogbert
  • 212,659
  • 41
  • 396
  • 397
0

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.

Kenan Banks
  • 207,056
  • 34
  • 155
  • 173