Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a list to itself in Python

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

like image 259
Double AA Avatar asked Jul 22 '11 17:07

Double AA


2 Answers

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

like image 164
Stefan Kanev Avatar answered Nov 13 '22 12:11

Stefan Kanev


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

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

like image 26
Amber Avatar answered Nov 13 '22 10:11

Amber