LoginSignup
1
0

More than 1 year has passed since last update.

PythonのSubscriptableなオブジェクトとIterableなオブジェクトの違い

Posted at

きっかけ

TypeError: XXXX object is not subscriptable
となってしまったのはなぜ?

定義

Iterable

一度に自分のメンバーをリターンすることのできるオブジェクトのこと。
__iter__()メソッドや__next__()メソッドを持つ。
StrもIterableである。

Subscriptable

obj[key]でメンバーを取得できるオブジェクトのこと。ListやDictionaryもSubscriptableである。
__getitem__()メソッドを持つ。

関係性

Iterable ⊂ Subscriptable
である。つまり、IterableではあるがSubscriptableではないブジェクトがある。
例えばsetである。setオブジェクトは順番を保証しないので、当然インデックスも存在しない。よって次のようにiterationできるのに、インデックスを指定するとnot subscriptableというエラーが出る。

se = {'aa','bb','cc'}
for x in se:
  print(x)

aa
bb
cc

となるが、

se = {'aa','bb','cc'}
print(se[0])

TypeError: 'set' object is not subscriptable

である

1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0