list index()

Michael L Torrie torriem at
Sat Sep 1 21:37:29 CEST 2007

zzbbaadd at wrote:
> In my case of have done os.listdir() on two directories. I want to see
> what files are in directory A that are not in directory B.
> I have used exceptions in other languages and only do so on logic that
> should never happen. In this case it is known that some of the files
> will not be in both lists. I just want to know which ones.

What's wrong, then, with doing:

if i in list:
   print list.index(i)

Since if, as you proposed, list.index() returned some value to represent
 "not found", you'd require an if anyway.

This is probably not pythonic, but at least it would overcome your
exceptions excuse.

If we were to program this .index() method in some language that
enforces contracts, like haskell, then we'd say that .index() expects a
value that exists in the list.  So if you violate the contract, why
should you expect to *not* get an exception.  Doing it any other way,
though, makes the code a lot more error prone.

More information about the Python-list mailing list