Please check my understanding...
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Tue Jul 1 16:50:34 EDT 2008
On Tue, 01 Jul 2008 12:35:01 -0700, Tobiah wrote:
> list.append([1,2]) will add the two element list as the next
> element of the list.
>
> list.extend([1,2]) is equivalent to list = list + [1, 2]
> and the result is that each element of the added list
> becomes it's own new element in the original list.
It's not 100% equivalent because `list.extend()` mutates the original list
while ``+`` creates a new list object:
In [8]: a = [1, 2, 3]
In [9]: b = a
In [10]: b.extend([4, 5])
In [11]: b
Out[11]: [1, 2, 3, 4, 5]
In [12]: a
Out[12]: [1, 2, 3, 4, 5]
In [13]: b = b + [6, 7]
In [14]: b
Out[14]: [1, 2, 3, 4, 5, 6, 7]
In [15]: a
Out[15]: [1, 2, 3, 4, 5]
> Is that the only difference?
>
> From the manual:
>
> s.extend(x) | same as s[len(s):len(s)] = x
>
> But: (python 2.5.2)
>
>>>> a
> [1, 2, 3]
>>>> a[len(a):len(a)] = 4
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: can only assign an iterable
>>>>
Have you tried `extend()` with the same value?
In [15]: a
Out[15]: [1, 2, 3, 4, 5]
In [16]: a.extend(6)
---------------------------------------------------------------------------
<type 'exceptions.TypeError'> Traceback (most recent call last)
/home/bj/<ipython console> in <module>()
<type 'exceptions.TypeError'>: 'int' object is not iterable
See, both ways need something iterable.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list