高校物理160203 views
高校国語788336 views
高校化学2924392 views
雑学1473612 views
高校日本史190571 views
小学社会310485 views
英語613639 views
小学算数1200427 views
りんご209490 views
高校生物551766 views
Help
Tools
NewsSpreadsheetCalendarSlidesTier ListPen ToolIllustrationCrayonPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsCross SectionsMotion PathMechanicsWavesLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic Theory

English

Pythonのリスト:インデックスを指定して値を取得する

前回は数値や文字列を並べたリストというものを紹介しました。今回はリストの中身を取りだす方法を考えます。

a = [4, 9, 12, 37, 56]

print(a[0])
print(a[1])
print(a[2])
print(a[3])
print(a[4])

a[0]はaというリストの1番目を表します。a[1]ではなくa[0]であることに注意してください。同じようにa[1]はaの2番目を表します。上のプログラムの出力結果は

4
9
12
37
56

となります。この0から4をリストのインデックスといいます。

インデックスが要素数を超えたらどうなるか?

a = [4, 9, 12, 37, 56]
print(a[5])

はどのような出力結果になるでしょうか?

Traceback (most recent call last):
File “list_2.py”, line 8, in
print(a[5])
IndexError: list index out of range

aは0から4までしか要素を持たないので、a[5]は存在しません。ここで無理やりa[5]を出力させようとすると、コンソール画面に上のようなIndexErrorというエラーが表示されます。

文字列のリストは?

b = [‘りんご’, ‘みかん’, ‘メロン’]

print(b[0])
print(b[1])
print(b[2])

上の出力結果は

りんご
みかん
メロン

となります。しかしインデックスが2を越えると

b = [‘りんご’, ‘みかん’, ‘メロン’]

print(b[0])
print(b[1])
print(b[2])
print(b[3])

りんご
みかん
メロン
Traceback (most recent call last):
File “list_2.py”, line 6, in
print(b[3])
IndexError: list index out of range

となり、IndexErrorというエラーが出ます。

Pythonのリストでそれぞれの値を出力するにはa[2]のようにカッコを使います。カッコ内の値をインデックスといいます。