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

for 文の基本:リストを一つずつ取り出す【Day 10】

Last updated at Posted at 2025-12-09

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day10 の記事です。

for 文の基本:リストを一つずつ取り出す

for 文は「繰り返し処理」を書くための仕組みです。
特に リストの中身を1つずつ取り出す用途が最もよく使われます。

for 文の基本形

for 変数 in リスト:
    処理

リストの要素が 先頭から順に 変数に入ります。

基本例:リストの中身を順番に表示

fruits = ["apple", "banana", "orange"]

for f in fruits:
    print(f)

実行結果:

apple
banana
orange

変数名は「中身がわかる名前」にする

users = ["Alice", "Bob", "Charlie"]

for user in users:
    print("Hello,", user)

わかりやすい変数名は読みやすさを大きくアップさせます。

数値リストでもOK

numbers = [1, 2, 3, 4]

for n in numbers:
    print(n * 2)

for 文内の処理はインデントが必須

for x in [1, 2, 3]:
print(x)   # NG(インデントなし)

正しくは:

for x in [1, 2, 3]:
    print(x)

よくあるエラー

1. リストではなく文字列を回してしまう

for c in "hello":
    print(c)

これはエラーではありませんが、文字が一文字ずつ取り出されてしまいます。

2. コロン : を忘れる

for item in items   # NG

まとめ

  • for 文は「リストの要素を1つずつ処理する」のに最適
  • for 変数 in リスト: の形を覚える
  • インデントとコロンを忘れない
  • 変数名は意味のわかる名前にすると読みやすくなる
1
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
1
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?