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.

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Apr 20, 2020 at 15:26
3
  • Could you please define the variables n and source? Commented 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. Commented Apr 20, 2020 at 22:09
  • stackoverflow.com/help/someone-answers Commented Jan 15, 2024 at 7: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)
answered Apr 20, 2020 at 16:27
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)))
answered Jan 15, 2024 at 15:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.