Newbie: tuple list confusion.

Dan Perl dperl at rogers.com
Sun Sep 12 22:04:34 EDT 2004


I would have expected the same results as you, but then, after all, I'm 
still a newbie myself.

But here is how I understand it now.  a=a+b and a+=b are not the same.  The 
first one creates a new list and assigns it back to 'a'.  The second one is 
changing 'a' in-place and is probably equivalent to a.extend(b).

Here is some code to prove that a is changed in-place in the second case:
    a=[1,2,3]
    c=a
    print a,c                  # [1, 2, 3] [1, 2, 3],  a and c are the same 
object
    a.append(4)
    print a,c                  # [1, 2, 3, 4] [1, 2, 3, 4],  I told you so!
    b=[5,6,7]
    a=a+b
    print a,c                  # [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4],  a and 
c are not the same object anymore
    a=c
    print a,c                  # [1, 2, 3, 4] [1, 2, 3, 4],  a and c are the 
same object again
    a+=b
    print a,c                  # [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 
7],  still the same object!
    b=(8,9)                   # let's show it with a tuple too
    a+=b
    print a,c                  # [1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 
6, 7, 8, 9]


Dan


"Q852913745" <q852913745 at aol.com> wrote in message 
news:20040912195529.03437.00000338 at mb-m27.aol.com...
>I am trying to learn python from 'Python programming for the absolute 
>beginner'
> I'm sure I understand the difference between tuples and lists, but while
> experimenting with what I have learned so far, I was suprised that this 
> code
> worked.
>
> # Create list a
> a=["start",878,"item 1",564354,"item 2"]
> print "length of list a =",len(a)
> print "a =",a ; print
>
> # Create tuple b
> b=(234,"item 3",456,"end")
> print "length of tuple b =",len(b)
> print "b =",b ; print
>
> print "Add b onto a"  # Shouldn't work!
> #---------------------------------------------
> # a=a+b    # causes an error as it should,
> a+=b      # but why is this ok?
> #---------------------------------------------
> print "a =",a
> print "length of a =",len(a)
> print;c=raw_input("Press enter to exit")
>
> My book states that a=a+b and a+=b are the same, and that different 
> 'types' of
> sequence cannot be joined together. 





More information about the Python-list mailing list