Newbie Question, list = list + x VS append (x)
Duncan Booth
duncan at rcp.co.uk
Fri Nov 29 04:39:50 EST 2002
Chuck <cdreward at riaa.com> wrote in
news:mh4euu095fqqm9bmcgrpdrcvb5emgpkhlm at 4ax.com:
> def add2(n):
> return [n+2]
>
> x = y = [1,2]
>
> print x # [1,2] - Ok
>
> x = x + add2(5)
>
> print x # [1,2,7] - why not [1,2,[7]]? add2 returns answer inside
"[ ]"
>
>
> #...vs...
>
>
> print y # [1,2] - Ok
>
> y.append( add2(5) )
>
> print y # [1,2,[7]] - Ok; What I expected it to do
>
>
> I'm not clear what's going on when I do "list = list + function
that
> returns list", i.e. why it's taking the 7 out of a list, where
.append
> keeps it in...
Ignore the function for now, it is just confusing you.
>>> x = [1, 2] + [7]
>>> print x
[1, 2, 7]
>>> y = [1, 2]
>>> y.append([7])
>>> print y
[1, 2, [7]]
>>>
The + operator concatenates lists. i.e. it takes two lists and
sticks them together as a single list. In your case you had a single
element, but if the second list had been longer it might be more
obvious:
>>> print [1, 2] + [7, 8, 9]
[1, 2, 7, 8, 9]
The append method of a list takes one object of any type, and puts
that object on the end of the list.
Note that in the first case, using + to concatenate lists, both
arguments to + must be lists but the second case doesn't care.
The 'extend' method of lists is the one that corresponds more
closely to '+' than the append method, (although of course it
modifies in place rather than creating a new list):
>>> x = y = [1, 2]
>>> x.extend([7,8])
>>> print x
[1, 2, 7, 8]
>>> print y
[1, 2, 7, 8]
>>>
More information about the Python-list
mailing list