[Tutor] Location of found item in list.

Luke Paireepinart rabidpoobear at gmail.com
Fri Oct 20 00:17:33 CEST 2006

Chris Hengge wrote:
> This is the solution I came up with.
>     for dirItem in directoryList:
>         directoryListLower.append(dirItem.lower())
>     #---Loop for file name comparison.
>     for item in lineList: # For every item in the 'lineList'
>         if item in directoryList: # If the item is also in 'directoryList'
>             # Print out so I know it is found.
>             print match.ljust(20) + item.ljust(20) \
>             + directoryList[directoryList.index (item)]
>         else: # If it isn't found, print what didn't match.
>             # Use the lowercase form from each list to find what 
> didn't match.
>             if item.lower() in directoryListLower:
>                 # Print out so I can see why it failed.
>                 print fail.ljust(20) + item.ljust(20) + \
>                     directoryList[directoryListLower.index(item.lower())]
>                 os.rename(pathName + \
>                     directoryList[directoryListLower.index 
> (item.lower())], \
>                         pathName + item)
It looks like it would do what you wanted.
The lines are a little long, but sometimes that can't be helped.
If you could come up with shorter variable names that were still 
maybe that would help.

also, you can use a list comprehension for the first two lines:
directoryListLower = [item.lower() for item in directoryList]

IF you're not familiar with list comprehensions this may look a tad scary,
but once you learn them, you'll be pleased to see something in this form :)
also, I assume you initialized directoryListLower at some other point in 
the code,
since append() doesn't work unless the variable is tied to a list object,
so in this syntax you could skip that line as well.

I'm not really sure why you don't want to use an inner loop, so you 
don't have to use the index,
but I guess 'to each his own'.

I'd probably do it this way:

for line in lineList:
    found = False
    for filename in directoryList:
       if line.lower() == filename.lower():
          found = True
          if line == filename: #an exact match
             print "%s is already set to %s" % (line,filename)
             #add a break here if you want :)
          else:#we found the right directory entry, but we need to 
change the case.
             print "Changing  %s to %s." % (filename,line)
             #add a break here if you want :)
    if not found:
       print "The item %s wasn't found in the directory listing." % line

Then you don't need the intermediate list of lowered items,
and you don't have those really long indexing lines.

But your way is fine :)
Good luck on your future Python endeavours.

More information about the Tutor mailing list