The Python Oracle

What does it mean if a Python object is "subscriptable" or not?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 What Does It Mean If A Python Object Is &Quot;Subscriptable&Quot; Or Not?
00:13 Accepted Answer Score 588
00:35 Answer 2 Score 114
00:55 Answer 3 Score 26
02:06 Answer 4 Score 21
02:39 Answer 5 Score 11
02:53 Thank you

--

Full question
https://stackoverflow.com/questions/2169...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #terminology

#avk47



ACCEPTED ANSWER

Score 590


It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.




ANSWER 2

Score 114


Off the top of my head, the following are the only built-ins that are subscriptable:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

But mipadi's answer is correct - any class that implements __getitem__ is subscriptable




ANSWER 3

Score 21


if “scriptable”

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

if “subscriptable”

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).




ANSWER 4

Score 11


I had this same issue. I was doing

arr = []
arr.append["HI"]

So using [ was causing error. It should be arr.append("HI")