remove a list from a list

Rares Vernica rvernica at gmail.com
Fri Nov 17 21:00:46 CET 2006


Sorry for not being clear from the beginning and for not using clear 
variable names.

Problem context:

import os
dirs_exclude = set(('a', 'b', 'e'))
for root, dirs, files in os.walk('python/Lib/email'):
     # Task:
     # delete from "dirs" the directory names from "dirs_exclude"
     # case-insensitive

The solution so far is:

for i in xrange(len(dirs), 0, -1):
   if dirs[i-1].lower() in dirs_exclude:
     del dirs[i-1]

I am looking for a nicer solution.

Thanks a lot,
Ray

Tim Chase wrote:
>> Yeah, I ended up doing a similar kind of loop. That is pretty messy.
>>
>> Is there any other way?
> 
> I've already provided 2 (or 3 depending on how one counts) 
> solutions, each of which solve an interpretation of your original 
> problem, neither of which involve more than 3 lines of fairly 
> clean code.  Perhaps a little more context regarding what you 
> *want* to do would help.  However, I suspect that answer is 
> "there is no *cleaner* way to do it".
> 
> Unless you're modifying an existing list that is referenced 
> elsewhere, the reassignment (l = [x for x in l ...]) solution 
> should work just fine.  Thus, unless you have a situation akin to:
> 
> 	g = l
> 	l = [x for x in l if x.lower() not in s]
> 	assert(thing_from_s not in g)
> 
> then just reassign "l".  If not, use the loop.  It's that easy 
> and clean.  Don't try to opaquify it by collapsing it further. 
> Perhaps, if your loop is messy, use my clean loop suggestion.
> 
> -tkc
> 
> 
> 




More information about the Python-list mailing list