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 1 year has passed since last update.

リストのforループで頭に入れておくこと

Posted at

paizaをやるにあたって覚えておきたいことをメモする

下記のコードはエラーが出てしまう

data_list = ['lion','tiger','cat','dog','human']

for i in data_list:
    print(data_list[i])
# TypeError: list indices must be integers or slices, not str

forループでinの次にリストを置いた場合、iはその要素そのものを表すため、わざわざリストを使い呼び出す必要がない

従って、

data_list = ['lion','tiger','cat','dog','human']

for i in data_list:
    print(i)
# lion
# tiger
# cat
# dog
# human

または

data_list = ['lion','tiger','cat','dog','human']

for i in range(len(data_list)):
    print(data_list[i])
# lion
# tiger
# cat
# dog
# human

こうすることで表示できる

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