Please check my understanding...

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Tue Jul 1 16:46:48 EDT 2008


On 1 juil, 21:35, Tobiah <t... at tobiah.org> wrote:
> list.append([1,2]) will add the two element list as the next
> element of the list.

list.append(obj) will add obj as the last element of list, whatever
type(obj) is.

> list.extend([1,2]) is equivalent to list = list + [1, 2]

Not quite. The second statement rebinds the name list (a very bad name
BTW but anyway...) to a new list object composed of elements of the
list object previously bound to the name list and the elements of the
anonymous list object [1, 2], while the first expression modifies the
original list object in place. The results will compare equal (same
type, same content), but won't be identical (not the same object).

A better definition for list.extend(iterable) is that it is equivalent
to:

for item in iterable:
   list.append(item)

The difference is important if list is bound to other names. A couple
examples:

a = [1, 2, 3}
b = a
# b and a points to the same list object
b is a
=> True

a.append(4)
print b
=> [1, 2, 3, 4]

b.extend([5, 6])
print a
=> [1, 2, 3, 4, 5, 6]

a = a + [7, 8]
print b
=> [1, 2, 3, 4, 5, 6]

print a
=> [1, 2, 3, 4, 5, 6, 7, 8]

a is b
=> False

def func1(lst):
    lst.extend([9, 10])
    print lst

def func2(lst):
    lst = lst + [11, 12]
    print lst

func1(a)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

func2(a)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


> Is that the only difference?

cf above.

> 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

And if you try with extend, you'll also have a TypeError:

a.extend(4)
=> Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not iterable


list.extend expects an iterable, and so does slice assignment.

You want:

a[len(a):len(a)] = [4]

>
> Also, what is the difference between list[x:x] and list[x]?

The first expression refers to the *sublist* starting at x and ending
one element before x. Of course, if x == x, then it refers to an empty
list !-)

>>> a[3:3]
[]
>>> a[1:3]
[2, 3]
>>> a[0:2]
[1, 2]
>>> a[0:1]
[1]
>>>

The second expression refers to the *element* at index x.

 HTH



More information about the Python-list mailing list