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?

enumerate / zip の便利な使い方【Day 16】

0
Last updated at Posted at 2025-12-15

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

enumerate / zip の便利な使い方

for 文と一緒に使うと便利な関数に enumeratezip があります。
どちらも Python 初心者が早めに覚えると得する機能です。

1. enumerate:番号つきでループしたいとき

リストをループしつつ インデックス(番号)も同時に取りたい 場面で便利です。

■ 例:番号つきで表示する

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

for index, fruit in enumerate(fruits):
    print(index, fruit)

出力例:

0 apple
1 banana
2 orange

■ start パラメータで始まりの番号を変える

for i, f in enumerate(fruits, start=1):
    print(i, f)
1 apple
2 banana
3 orange

2. zip:複数のリストを同時にループする

2つ以上のリストを「横にくっつける」イメージです。

■ 例:名前と年齢をまとめて処理

names = ["Alice", "Bob", "Charlie"]
ages = [24, 30, 29]

for name, age in zip(names, ages):
    print(name, age)

出力:

Alice 24
Bob 30
Charlie 29

■ zip の注意点

  • 一番短いリストに合わせてループが止まる
a = [1, 2, 3]
b = ["x", "y"]

for x, y in zip(a, b):
    print(x, y)

1 x2 y までで止まる。

3. enumerate と zip の組み合わせ

複数リストを使いながら番号もほしいとき。

for i, (name, age) in enumerate(zip(names, ages), start=1):
    print(i, name, age)

4. 今日のまとめ

  • enumerate:番号つきでループ
  • zip:複数リストを同時にループ
  • 初心者のうちから使えるとコードが読みやすくなる

5. ミニ問題

Q1. enumerate を使って次のリストを 1 から番号つきで表示してみてください。

colors = ["red", "blue", "green"]

Q2. zip を使って subjects = ["Math", "English"]scores = [80, 90] を組み合わせて表示するコードを書いてみてください。

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?