【Python】enumerate()関数で配列の要素とインデックス番号を取得

Pythonで配列の各要素をfor文で取得する場合は、以下のようにします。

colors = ['black', 'white', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan']

for c in colors:
    print(c)

(実行結果)

ここに、インデックス番号付きで各要素をする場合は

colors = ['black', 'white', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan']

i = 0
for c in colors:
    print(i, c)
    i += 1

(実行結果)

とも書けますが、Pythonのenumerate()関数を使うと

colors = ['black', 'white', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan']

for i, c in enumerate(colors):
    print(i, c)

(実行結果)

となります。

さらに開始値を0以外にしたい場合は、enumerate()関数の引数に開始値を追加し、

colors = ['black', 'white', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan']

for i, c in enumerate(colors, 11):
    print(i, c)

(実行結果)

とします。