1

I'm trying to calculate a field with concatenated strings from zipped lists but I'm having issues with syntax.

MyList1 = ['Orange', 'Red']
MyList2 = ['Purple', 'Green']

for x, y in zip(MyList1, MyList2):
    ...##Other code working with x, y
    arcpy.CalculateField_management(InputLyr, "ColorConcat", "Color: {} and Color: {}".format(x, y), "PYTHON_9.3")
    ...##More code working with x, y

I'm hoping to get my output, calculated, field to look like this:

|          ColorConcat            |
|---------------------------------|
| Color: Orange and Color: Purple |
|  Color: Red and Color: Green    |

The only other thing I've tried is using codeblocks, but I don't think that the codeblock will return x and y because they're not global variables. I've also tried simply using + to concatenate but I returned the same syntax error.

arcpy.CalculateField_management(InputLyr, "ColorConcat", "Color: " + x + " and Color: " + y, "PYTHON_9.3")
  • Where are you running this code? From ArcMap, ArcGIS Pro, Python Script Tool, Python Toolbox Tool, Python Addin? Please review tips on writing code snippets. By "zipped lists" do you mean two lists that have items that need to be matched using their order? – PolyGeo Jul 25 '18 at 21:47
  • I found how to zip lists at stackoverflow.com/questions/13704860/zip-lists-in-python - it's a function that I had not noticed before. – PolyGeo Jul 25 '18 at 22:43
  • What you show in your first code sample doesn't really make sense. It'll just calculate the ColorConcat to be the same x & y value for all the rows and then repeat calculating all the rows for the next x & y value, overwriting the previous calculation. Are you actually wanting to loop through each row? Does each element in your MyListN lists correspond to a row in your table? – user2856 Jul 26 '18 at 2:22
2

I think you should use the da.UpdateCursor instead of Field Calculator. It is much more powerful and versatile.

import arcpy
fc = 'C:\database.gdb\polygons' #Change
colorconcatfield = 'ColorConcat' #Change

MyList1 = ['Orange', 'Red']
MyList2 = ['Purple', 'Green']

colors = zip(MyList1,MyList2)

with arcpy.da.UpdateCursor(fc,colorconcatfield) as cursor:
    for row in cursor:
        try: 
            row[0] = "Color: {0} and Color: {1}".format(*colors.__next__()) #* is unpacking the tuple of colors
        except StopIteration: #In case there are more rows in fc than colors in lists
            row[0] = "No more colors in lists"
        cursor.updateRow(row)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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