[Tutor] Question regarding list editing (in place)

bob gailer bgailer at alum.rpi.edu
Tue Feb 5 20:15:40 CET 2008

David J. Weller-Fahy wrote:
> Let me know if this should be on the general python list.
> I'm playing with some python to iterate over a directory structure.  Part 
> of the directory structure should be ignored, and will have a period (.) 
> as the first character of the directory name.
> My solution was to use the following code.
> #v+
> for root, dirs, files in os.walk(data_dir()):
>      for n in xrange(len(dirs) - 1, -1, -1):
>          if dirs[n].startswith(u'.'):
>              del dirs[n]
> #v-
> This works.  But I'm wondering whether there is a simpler solution (rather 
> than walking the index backwards through the list) to removing items from 
> a list without replacing the list?  Specifically, I'm looking for 
> something that would be similar to the concept, "Remove every list item 
> that starts with X."
dirs = [dir for dir in dirs if not dir.startswith(u'.')]

Bob Gailer
919-636-4239 Chapel Hill, NC

More information about the Tutor mailing list