newbe question about lists

Moshe Zadka moshez at math.huji.ac.il
Sun Mar 5 00:46:36 EST 2000


On Sat, 4 Mar 2000, Fredrik S wrote:

> I type the following:
> >>>
> l1=["a1","a2","a3"]
> >>> l2=["a4","a5","a6"]
> >>> l3=l1
> >>>
> l3[1:1]=l2
> >>> l3
> ['a1', 'a3', 'a4', 'a2']
> >>> l1
> ['a1', 'a3',
> 'a4', 'a2']
> 
> QUESTION:
> Why is value of l1 changed... The only
> thing I can think of is B U G ...

Well, actually it's a F E A T U R E.

You apparently don't understand the semantics of Python's assignment.
Python's model is that of references: a variable does not denote a
location in memory in which a value is stored, but is just a label stuck
to some location in memory. "l2=l1" means to take the label "l2" and 
stick it to the location which has the label "l1", and so forth.
On the other hand, statements like "l1[1:1]=something" mean "take the
object with the label l1, and kindly ask it to put something between
its first and its first element". Also, you do realize that Python lists
start at 0?

--
Moshe Zadka <mzadka at geocities.com>. 
http://www.oreilly.com/news/prescod_0300.html





More information about the Python-list mailing list