Friday, February 22, 2013

Creating a List with n number of entries (Python)

Normally when you create a list object in python, you cannot specify the number of items in the object by default unlike say an array object in C# or C++.  I recently ran into a situation where I was using the arcpy.da cursor objects for table that could have n number of fields.  I wanted the row to be initialized with a default value, so I used the * operator on the list to multiply a single value into a multi-value list.

Example:

# Get a list of fields that are not BLOB, OBJECTID, RASTER, GEOMETRY or GUID
fields = [field.name for field in arcpy.ListFields(service_table) \
                  if not(field.type.upper() in ['BLOB', 'OID', 'RASTER','GEOMETRY','GUID'])
# create a row list with default values
row = [""]* len(fields)

This will create a list object called row, where each value by default is an empty string ("").

Enjoy