1

Instead of doing:

        arcpy.AddField_management(source, "FIELD_1", "TEXT", "", "", 5)
        arcpy.AddField_management(source, "FIELD_2", "TEXT", "", "", 5)
        arcpy.AddField_management(source, "FIELD_3", "TEXT", "", "", 10)
        arcpy.AddField_management(source, "FIELD_4", "TEXT", "", "", 4)
        arcpy.AddField_management(source, "FIELD_5", "TEXT", "", "", 100)
        arcpy.AddField_management(source, "FIELD_6", "TEXT", "", "", 150)

I want to loop through and create all these fields in one step.

So far I have something along the lines of:

        new_fields = ["FIELD_1", "FIELD_2", "FIELD_3", "FIELD_4", "FIELD_5", "FIELD_6"]
        field_length = [5, 5, 10, 4, 100, 150]

        for n in new_fields:
            arcpy.AddField_management(source, n, "TEXT", "", "", field_length)

But I am getting an error: Object: Error in executing tool

I believe it's because I have the field lengths in a list, but I'm not sure on the proper syntax to do this.

3
  • Could you please define the variables n and source?
    – Aaron
    Apr 20, 2020 at 16:07
  • 1
    You don't say which version of arcpy you are using, you should always state that and license level in any question, because if you were using ArcPro you could use the AddFields tool.
    – Hornbydd
    Apr 20, 2020 at 22:09

2 Answers 2

2

Loop over both lists using zip:

new_fields = ["FIELD_1", "FIELD_2", "FIELD_3", "FIELD_4", "FIELD_5", "FIELD_6"]
field_length = [5, 5, 10, 4, 100, 150]

for field, length in zip(new_fields, field_length):
    print field, length
FIELD_1 5
FIELD_2 5
FIELD_3 10

And include the parameter names:

for name, length in zip(new_fields, field_length):
    arcpy.AddField_management(in_table=source, field_name=name, field_type="TEXT", field_length=length)
0
1

As mentioned by @Hornbydd in the comments, a better approach with ArcGIS Pro would be to use Add Fields (multiple) (Data Management) - ArcGIS Pro | Documentation.

names = ["FIELD_1", "FIELD_2", "FIELD_3", "FIELD_4", "FIELD_5", "FIELD_6"]
types = ["TEXT"]*6
aliases = [""]*6
lengths = [5, 5, 10, 4, 100, 150]

arcpy.management.AddFields(source, list(zip(names, types, aliases, lengths)))

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.