見出し画像

【Python】イテラブル(iterable)って、なに?

「for 文の in にできるもの」

個人的にはこのように解釈しました。

完全に一致するのかはわからないんですけど。
もし、
 for 文の in にはできるけどイテラブルでないもの
とか
 for 文の in にはできないけどイテラブルなもの
がありましたらご指摘いただけると幸いです。

イテラブルな型にはどういうものがあるのでしょうか。
例えば、
 イテレータ型
 オブジェクト型
 シーケンス型
 テキストシーケンス型
 バイナリシーケンス型
 集合型
 マッピング型
などなど。

なんというのか、ずいぶんたくさんあります。

イテレータ型、ジェネレータ型は組み込み型にはないようですので、別の記事で書きます。
他の型について見てみます。
それぞれ、コードと実行結果を記載します。

シーケンス型 list

a = [1, 2, 3]
print('type of a is ' , type(a))
for item in a:
    print(item)
type of a is <class 'list'>
1
2
3

シーケンス型 tuple

a = (1, 2, 3)
print('type of a is ' , type(a))
for item in a:
    print(item)
type of a is <class 'tuple'>
1
2
3

シーケンス型 range

a = range(1, 4)
print('type of a is ' , type(a))
for item in a:
    print(item)
type of a is <class 'range'>
1
2
3

テキストシーケンス型 str

a = 'ab cdef'
print('type of a is ' , type(a))
for item in a:
    print(item)
type of a is <class 'str'>
a
b

c
d
e
f

バイナリシーケンス型 bytes

a = b'ab cdef'
print('type of a is' , type(a))
for item in a:
    print(item)
type of a is <class 'bytes'>
97
98
32
99
100
101
102

バイナリシーケンス型 bytearray

a = bytearray([1, 2, 3])
print('type of a is' , type(a))
for item in a:
    print(item)
type of a is <class 'bytearray'>
1
2
3

集合型 set

a = {1, 2, 3}
print('type of a is' , type(a))
for item in a:
    print(item)
type of a is <class 'set'>
1
2
3

マッピング型 dict

a = {'apple':1, 'orange':2, 'banana':3}
print('type of a is' , type(a))
for item in a:
    print(item)
type of a is <class 'dict'>
apple
orange
banana


この記事が気に入ったらサポートをしてみませんか?