0

I have a bunch of feature classes in a geodatabase, and some of them are empty. I want to generate a list of all feature class names, and then remove the names of any feature classes that are empty. For some reason, the (example) code below removes some, but not all of the empty files.

These lines correctly produce a list of all the feature classes:

myDir = r'C:\Projects\geodatabase.gdb'
arcpy.env.workspace = myDir
myfiles = 'MLresult_*' 
file_list = arcpy.ListFeatureClasses(myfiles)

If I print the name and the number of records of all files in the list...

for file in file_list:
    print(file)
    print(arcpy.management.GetCount(file))

The printout is something like:

MLresult_2013
9
MLresult_2018
4
MLresult_2020
0
MLresult_2021
0

Where multiple files are empty (and the counts are all correct). BUT, when I execute these lines...

for file in file_list:
    if arcpy.management.GetCount(file)[0] == "0":
        file_list.remove(file)

then the list removes some of the "empty" files, but not all, so the list now looks like:

['MLresult_2013', 'MLresult_2018', 'MLresult_2021']

Why would it remove MLresult_2020, but not MLresult_2021, when

arcpy.management.GetCount(file)[0] == "0"

Is true for both?

6
  • 1
    What is fileB_list? Commented Jan 12, 2022 at 17:47
  • 2
    Shouldnt == "0" be == 0?
    – Bera
    Commented Jan 12, 2022 at 18:15
  • 2
    Shapefiles can't be in a geodatabase (different formats). Did you mean "feature classes"?
    – Vince
    Commented Jan 12, 2022 at 18:35
  • @Kadir -- that fileB_list is a typo, I missed it when modifying my actual code for this forum. It is not the reason the code fails.
    – Sarah T
    Commented Jan 19, 2022 at 15:47
  • 1
    stackoverflow.com/questions/6260089/… Commented Jan 19, 2022 at 16:05

1 Answer 1

4

Python behind the scenes creates an iterator for your list, and it is the iterator which moves through your list one entry at a time. The iterator is evaluated once, which means that if you then modify your list, the iterator could potentially get ‘lost’ - you also can't use the file variable to modify your list, since it is just a reference to the thing in your list.
Reference

You should avoid modifying a list in for loop using its element in the loop, especially avoid removing an item from the list.

You can solve the issue using a list comprehension:

file_list = arcpy.ListFeatureClasses(myfiles)

# list comprehension
file_list = [f for f in file_list if arcpy.management.GetCount(f)[0] != 0]

But this doesn't remove empty feature classes from the geodatabase. It just removes the items from file_list list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.