lstFields = arcpy.ListFields(fc) x = False for field in lstFields: if field.name == "USNG": print "Field exists" x = True if x <> True: print "Field does not exist"
lstFields = arcpy.ListFields(fc) if "USNG" in lstFields: print "Field exists" else: print "Field does not exist"
>>> a = [3,5,6,'kitty'] # a Python list >>> b = 2 >>> b in a False >>> c = 5 >>> c in a True >>> d = 'kitty' >>> d in a True >>>
This is the most direct. Your code is so clear and concise. Well done!
Stacy's arcpy.ListFields returns a list of field objects (not field names) so the "in" operator would not work. You could make it work by converting the list to field names (and converting to upper case because the in operator is case sensitive).
lstFields = arcpy.ListFields(fc)
field_names = [f.name.upper() for f in lstFields]
if "USNG" in field_names:
print "Field exists"
else:
print "Field does not exist"
Tested Stacy's code above and curtvprice is correct, the "in" operator will not work.
if arcpy.ListFields(tbl, field_name): print "Field exists" else: print "Field doesn't exist"
This code worked for me. Using a couple for loops I was able to run this against multiple feature classes within multiple feature datasets to determine if a field was present.