Please check my understanding...

Matimus mccredie at gmail.com
Tue Jul 1 22:23:54 CEST 2008


On Jul 1, 12:35 pm, Tobiah <t... at tobiah.org> 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.
>
> 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
>
>
>
> Also, what is the difference between list[x:x] and list[x]?
>
> >>> a[3:3] = [4]
> >>> a
>
> [1, 2, 3, 4]
> ** Posted fromhttp://www.teranews.com**

In this example:
> s.extend(x)  |  same as s[len(s):len(s)] = x

x _must_ be iterable. As the error states, `4` is not iterable.

the s[start:stop] notation is called slicing:

>>> x = range(10)
>>> x[0]
0
>>> x[1]
1
>>> x[0:1]
[0]
>>> x[0:2]
[0, 1]
>>> x[0:3]
[0, 1, 2]
>>> x[1:3]
[1, 2]
>>> x[5:-1]
[5, 6, 7, 8]
>>> x[5:]
[5, 6, 7, 8, 9]


In general `x[len(x):len(x)] = seq` is a stupid way to extend a list,
just use .extend or +=.

Matt



More information about the Python-list mailing list