I am coping with a shapefile and I want to select some rows if the values in one column are in a Python list. The following gives the code I write:

tpu_involved = list(set(dataframe['SmallTPU']))
selection_expression = '"SmallTPU" IN ({0})'.format(', '.join(map(str, tpu_involved)) or 'NULL')
print('The invalid expression is: {}'.format(selection_expression))
selected_layer = arcpy.SelectLayerByAttribute_management(in_layer_or_view='tpu_lyr',

The tpu_lyr is the layer which is loaded from a local shapefile. I have checked some previous questions like Selecting features by attribute if in Python list?, but it still does not work.

  • 1
    try '"SmallTPU" IN ({0}) OR "SmallTPU" IS NULL'.format(... – BERA Jul 27 '19 at 14:52
  • Thank you for your prompt reply! Finally, I use the following codes: Python tpu_list = list(dataframe['SmallTPU']) tpu_changed = tuple([item.encode('utf-8') for item in tpu_list]) selection_expression = """ "SmallTPU" IN {} """.format(tpu_changed) You need to encode the string first... – Bright Chang Jul 28 '19 at 12:16
  • Nice, you can post that as an answer to your own question – BERA Jul 28 '19 at 18:52

Your Answer

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

Browse other questions tagged or ask your own question.