0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

list の「値」と「index値」の両方を取得する方法(enumerate()関数)

0
Posted at

list の「値」と「index値」両方を取得する方法について、
以下の2パターンで紹介する。

  1. for文の変数を使って取得する方法
  2. enumerate()関数を使って取得する方法
     

1. for文の変数を使って取得する方法
for文の変数を使ってlist内の「値」とその「index値」を求めるには、
以下のようなコードになる。

array = [10, 20, 30]

# for文の変数を使って「index値」と「値」の両方を取得する
for i in range(len(array)):
    print("index値が", i, "の値は", array[i])

実行結果は以下の通り。

index値が 0 の値は 10
index値が 1 の値は 20
index値が 2 の値は 30

 

2. enumerate()関数を使って取得する方法
続いてenumerate()関数を使って「値」と「index値」を取得する。

array = [10, 20, 30]
    
# enumerate() 関数を使って「index値」と「値」の両方を取得する
for index, value in enumerate(array):
    print("index値が", index, "の値は", value)

実行結果は以下の通り。

index値が 0 の値は 10
index値が 1 の値は 20
index値が 2 の値は 30

for文の変数を使った場合と同じ結果を得ることができたが、
enumerate()関数を使った方が「値」と「index値」を別々に管理出来るので
より複雑なコードを書いた場合などには、理解しやすいかもしれない?

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?