Error "'type' object has no attribute '__getitem__'" when iterating over list["a","b","c"]

33,571

Solution 1

This line is your problem:

lst=list["ram","bak","cat","fas","far","fmk","sup","gro","ebt"]

Python interprets what's in those square brackets as a key to get an item from what's just before them—in this case, getting the item with key "ram", "bak", ... from list. And, of course, the list class isn't a container and doesn't have any items!

Remove the leading list, and you get a list literal, which is probably what you want.

list_ = ["ram", "bak", "cat", "fas", "far", "fmk", "sup", "gro", "ebt"]

See the documentation on lists for more information on how to create them.

See also the official Python style guide, which states

  • names that would otherwise collide with keywords or builtins (like list) should have single underscores appended rather than being mangled (list_ instead of lst or lizt), except in the case of cls

  • container literals and function calls should have spaces after the commas ("ram", "bak" instead of "ram","bak")

Solution 2

To define a list,

lst=["ram","bak","cat","fas","far","fmk","sup","gro","ebt"]

or

lst=list(...)

but list is a type, which you can call with parenthesis but you can't get an item from list using the square brackets.

Share:
33,571
April
Author by

April

Updated on April 16, 2020

Comments

  • April
    April about 4 years

    I'm new to Python and I keep getting this error:

    TypeError: 'type' object has no attribute '__getitem__'
    

    when I try to run this code:

    import arcpy,os
    from arcpy import env
    from arcpy.sa import*
    env.workspace="F:\U of M\good good study\python\fl\fl"
    inFeatures="foodpts.shp"
    lst=list["ram","bak","cat","fas","far","fmk","sup","gro","ebt"]
    for item in lst:
        populationField=item
        cellsize=100
        searchRadius=805
        arcpy.CheckOutExtension("Spatial")    
        outKernelDensity=KernelDensity(inFeatures,populationField,cellsize,searchRadius,  "SQUARE_KILOMETERS")
        outKernelDensity.save("F:\U of M\good good study\python\fl\fl\kernal")
    

    What am I doing wrong?