[Tutor] two ways

Gregor Lingl glingl at aon.at
Fri Nov 11 11:24:19 CET 2005


Liam Clarke schrieb:

>Hi Shi,
>
>For what you're doing, nothing at all.
>
>When you use a colon, slice syntax, it defaults to [start:end] so p =
>a[:] is the same as
>p = a[0:len(a)]
>
>  
>
But in fact there is a difference. I'll show you:

 >>> a=range(5)    ### creates a list-object
 >>> id(a)             ### which has an identity
14716520  
 >>> p=a              ### creates the new name p for the same object
 >>> id(p)            ### let's see
14716520           ### o.k. really the same
 >>> q=a[:]          ### this names a *copy* of a q
 >>> id(q)            ### identity?
14714840           ### different!
 >>> a is p           ### check if objects named a and p are identical
True                    ### yes
 >>> a is q          ### check if objects named a and q are identical
False                  ### no!
 >>> a == q 
True                   ### but have the same "content", i. e. two 
different list-objects with the same elements
 >>>
 >>>    ### Beware, lists are mutable:
 >>>
 >>> a
[0, 1, 2, 3, 4]
 >>> a[1]=1001
 >>> a
[0, 1001, 2, 3, 4]
 >>> p
[0, 1001, 2, 3, 4]    ### object named a *and* p is changed
 >>> q                     ### copy q of a is not changed!°
[0, 1, 2, 3, 4]
 >>>
regards
Gregor


More information about the Tutor mailing list