[Tutor] detecing palindromic strings

wesley chun wescpy at gmail.com
Sun Sep 30 09:51:36 CEST 2007


greetings, and welcome to Python!

there were some good solutions using the extended slice operator
([::-1]), but that may be an obscure notation to many newbies to
Python, as powerful as it can be.

i'm going to pick up terry's response and further clarify here (i hope!):

> string_list_orig = string_list

this is a critical assignment.  and yes, you already figured out that
you are just "copying pointers" here.  in Python, we say that you are
creating an alias or another reference to the same object.  you are
not creating a new one which is a copy.  there are a couple of ways to
do the copy.

1. terry already mentioned string_list[:] takes an improper (or
complete) slice of the existing string
2. kent also chimed in with list(string_list), which will do exactly the same
3. more off the beaten path, you can also using copy.copy():

import copy
string_list_orig = copy.copy(string_list)

all 3 do exactly the same thing: create a new list but copy the
*references* to the internal objects.  these are known as "shallow
copies." they don't *copy* the contained objects themselves.  this is
another place that newbies go HUH?!?
the bottom line is that if the contained objects are mutable (meaning
their values can be altered), changing them from one reference will
affect the outcome via an alias.

in order to copy the container as well as its contents, you need to
use copy.deepcopy().  see the man page there for more details.
there's also a section in the book on this.


> string_list.reverse()

because both variable names reference the same object, doing this [or
string_list_orig.reverse()] will have the same effect.


> print string_list_orig
> print string_list

both "point" to the exact same object, hence the duplicate output.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list