前回は数値や文字列を並べたリストというものを紹介しました。今回はリストの中身を取りだす方法を考えます。
a = [4, 9, 12, 37, 56]
print(a)
print(a<figure style="padding-bottom: 5px;" class="article-image">
<img src="https://image.rollpie.com/2015/11/paku-book.jpg"
decoding="async" loading="lazy"
style="width: 320px; height: 215px;"
data-width="1000" data-height="669">
<figcaption style="width: 320px;">
<p class="figure-title">paku-book</p>
paku-okawa-peace
)
print(a

mencius
)
print(a

business-h2-1-01
)
print(a

)
aはaというリストの1番目を表します。a paku-book

paku-book
ではなくaであることに注意してください。同じようにa

はaの2番目を表します。上のプログラムの出力結果は
4
9
12
37
56
となります。この0から4をリストのインデックスといいます。
インデックスが要素数を超えたらどうなるか?
a = [4, 9, 12, 37, 56]
print(a<figure style="padding-bottom: 5px;" class="article-image">
<img src="https://image.rollpie.com/2015/11/business-h2-chokkan-01.png"
decoding="async" loading="lazy"
style="width: 320px; height: 28px;"
data-width="700" data-height="60">
<figcaption style="width: 320px;">
<p class="figure-title">business-h2-chokkan-01</p>
)
はどのような出力結果になるでしょうか?
Traceback (most recent call last):
File "list_2.py", line 8, in <module>
print(a<figure style="padding-bottom: 5px;" class="article-image">
<img src="https://image.rollpie.com/2015/11/business-h2-chokkan-01.png"
decoding="async" loading="lazy"
style="width: 320px; height: 28px;"
data-width="700" data-height="60">
<figcaption style="width: 320px;">
<p class="figure-title">business-h2-chokkan-01</p>
)
IndexError: list index out of range
aは0から4までしか要素を持たないので、a business-h2-chokkan-01

business-h2-chokkan-01
は存在しません。ここで無理やりa

を出力させようとすると、コンソール画面に上のようなIndexErrorというエラーが表示されます。
文字列のリストは?
b = ['りんご', 'みかん', 'メロン']
print(b)
print(b<figure style="padding-bottom: 5px;" class="article-image">
<img src="https://image.rollpie.com/2015/11/paku-book.jpg"
decoding="async" loading="lazy"
style="width: 320px; height: 215px;"
data-width="1000" data-height="669">
<figcaption style="width: 320px;">
<p class="figure-title">paku-book</p>
paku-okawa-peace
)
print(b

)
上の出力結果は
りんご
みかん
メロン
となります。しかしインデックスが2を越えると
b = ['りんご', 'みかん', 'メロン']
print(b)
print(b<figure style="padding-bottom: 5px;" class="article-image">
<img src="https://image.rollpie.com/2015/11/paku-book.jpg"
decoding="async" loading="lazy"
style="width: 320px; height: 215px;"
data-width="1000" data-height="669">
<figcaption style="width: 320px;">
<p class="figure-title">paku-book</p>
paku-okawa-peace
)
print(b

mencius
)
print(b

)
りんご
みかん
メロン
Traceback (most recent call last):
File "list_2.py", line 6, in <module>
print(b<figure style="padding-bottom: 5px;" class="article-image">
<img src="https://image.rollpie.com/2015/11/mencius.jpg"
decoding="async" loading="lazy"
style="width: 320px; height: 435px;"
data-width="353" data-height="479">
<figcaption style="width: 320px;">
<p class="figure-title">mencius</p>
)
IndexError: list index out of range
となり、IndexErrorというエラーが出ます。