[Tutor] Stuck on Something [Truth, falsehood, tuples!]

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 7 Mar 2001 19:56:37 -0800 (PST)


On Wed, 7 Mar 2001, David Porter wrote:

> >   File "C:\Program Files\Python20\Code\anotherftpthing.py", line 22, in ?
> >     dirs.append(string.split(x)[-1])
> > IndexError: list index out of range
> 
> Ah. This could be due to empty lines in raw_dirs. How about changing
> 
> for x in raw_dirs: 
>     dirs.append(string.split(x)[-1])
> 
>  TO
>     
> for x in raw_dirs: 
>     try:
>         dirs.append(string.split(x)[-1])
>     except IndexError:
>         pass    


Let's drive home the point:

###
>>> mystr = ''              
>>> l = string.split(mystr)
>>> l    
[]
>>> l[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list index out of range
###

I agree with David; this is probably the culprit.

An alternative way to fix the problem could be:

###
for x in raw_dirs: 
    if string.strip(x): dirs.append(string.split(x)[-1])
###

which says to append x to our list of directories only if, when we lay
that string bare, that there's still substance to it.  In Python, the
empty string, 0, the empty tuple, and the empty list are considered
"false" values:

###
>>> def isTrue(x):
...     if x: return 1
...     else: return 0
... 
>>> isTrue("")
0
>>> isTrue([])
0
>>> isTrue([[]])
1
###

But the big surprise I'm running into is this one:

###
>>> isTrue(())
0
>>> isTrue((()))
0
###

!! I can understand the empty tuple being false, but I can't rationalize
why the tuple containing an empty tuple would be also false!  Oh.  
Whoops.  That's because (()) is not a tuple that contains the empty tuple.

###
>>> isTrue(((),))
1
###

False alarm, sorry.  Gosh, I keep forgetting that tuples of one element
need to be disambiguated with the comma --- otherwise, Python thinks that
we're just trying to make a parenthesized expression.  Went way off course
on that one this time.  *grin*