Error “‘type’ object has no attribute ‘__getitem__'” when iterating over list[“a”,”b”,”c”]

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")

Leave a Comment