1
1

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 5 years have passed since last update.

forループ内でリストの添字と値を同時に取得できるenumerate

1
Posted at
foods = ["apple", "banana", "candy", "donuts"]

# こういうことをしたい
for i in range(len(foods)):
    print("foods[{}] = {}".format(i, foods[i]))
# foods[0] = apple
# foods[1] = banana
# foods[2] = candy
# foods[3] = donuts

# enumerateを使えばシンプル
for i, food in enumerate(foods):
    print("foods[{}] = {}".format(i, food))
# foods[0] = apple
# foods[1] = banana
# foods[2] = candy
# foods[3] = donuts

# 第二引数を与えるとiはその値から始まる
for i, food in enumerate(foods, 100):
    print("foods[{}] = {}".format(i, food))
# foods[100] = apple
# foods[101] = banana
# foods[102] = candy
# foods[103] = donuts

1
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?