[Tutor] sys.path.append

Andreas Kostyrka andreas at kostyrka.org
Thu Dec 18 18:16:37 CET 2008


Am Wed, 17 Dec 2008 11:17:14 -0500
schrieb "Kent Johnson" <kent37 at tds.net>:

> On Wed, Dec 17, 2008 at 10:20 AM, ppaarrkk <simon_ecc at yahoo.co.uk>
> wrote:
> >
> > I can do this :
> >
> >>>> sys.path.append ( 'C:\dump1' )
> 
> Note you should use raw strings r'C:\dump1' or double backslash
> 'C:\\dump1' because the \ is a string escape character.
> 
> > but not :
> >
> >>>> x = 'C:\dir1'
> >>>> sys.path.append(x)
> 
> That should work fine (other than the single \). What happens when
> you try it?
> 
> > or :
> 
> ??
> 
> > but not :
> 
> >>>> x = ['C:\dir1']
> >>>> sys.path.append(x)
> 
> Here you are appending a list of strings to sys.path, that will not do
> what you want.

The correct thing to do if you want to add a list of paths to sys.path
(btw, that probably is not what you want in real life, but that's a
complete different question.), you should do 

sys.path.extend(x)

which is an efficient way to do

for i in x:
    sys.path.append(i)

Or to visualize it with something simpler:

a = [1, 2, 3]
b = [4, 5, 6]
c = 7

a # [1,2,3]
a.append(c)
a # [1,2,3,7]
a.append(b)
a # [1,2,3,7,[4,5,6]]
a.extend(b)
a # [1,2,3,7,[4,5,6],4,5,6]

Basically append just appends it's parameter to the list, and if the
parameter happens to be a list, it appends the list as one item. Extend
on the other hand, appends all iterable items in the parameter to the
list.

Andreas


More information about the Tutor mailing list