Remove items from a list
Peter Abel
PeterAbel at gmx.net
Wed Sep 8 14:05:18 EDT 2004
"Stan Cook" <scook at elp.rr.com> wrote in message news:<ysv%c.32876$Dl4.14767 at fe2.texas.rr.com>...
> I was trying to take a list of files in a directory and remove all but
> the ".dbf" files. I used the following to try to remove the items, but
> they would not remove. Any help would be greatly appreciated.
>
> x = 0
> for each in dbases:
> if each[-4:] <> ".dbf":
> del each # also tried: del dbases[x]
> x = x + 1
>
> I must be doing something wrong, but it acts as though it is....
>
> signed
> . . . . . at the end of my rope....!
>
>
When you iterate over a list with a for-loop as you do it,
you get a copy of "each" item of the list. What you're doing
is deleting this copy, which is bound to the variable *each*.
If you want to delete an item of a list you have to code:
del dbases[i]
e.g
Example 1:
for i in range(len(dbases)):
if dbases[i][-4:] <> ".dbf":
del dbases[i]
But now you'll get some trouble: Youre indexing dbases from 0 .. len(dbases),
but len(dbases) will change everytime you delete an item. So the better way
is to run over the list from the end.
Example 2:
for i in range(len(dbases)-1,-1,-1):
if dbases[i][-4:] <> ".dbf":
del dbasese[i]
No you delete items of dbases, where the item indexed by i still exist.
As others already pointed out it would be better to write your condition
in a more general form:
Example 3:
for i in range(len(dbases)-1,-1,-1):
if dbases[i].endswith(".dbf"):
del dbasese[i]
Or still better to generate a new list with
listcomprehension
Example 4:
dbf_names=[name for name in dbases if name.endswith('.dbf')]
or the filter-function
Example 5:
dbf_names=filter(lambda name:name.endswith('.dbf'),dbases)
But I think the best way is to have in dbases only the filenames which
end with '.dbf' from the beginning. You can get this with the glob-modul
instead of os.listdir():
Example 6:
import glob
dbases=glob.glob('/any/path/or/directory/*.dbf')
You'll get only filenames in dbases which end with '.dbf' or
an empty list if there are none.
Regards
Peter
More information about the Python-list
mailing list