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?

【Python】メモリサイズを見てざっくりと理解するジェネレーター

Posted at

🎯 テーマ

  • for i in range(10) ← これ、実はジェネレーター(っぽい)動きしてます。
  • リストと比べてどれくらいメモリが違うの?
  • 実際に sys.getsizeof() を使って見てみよう!

🐢 まずは普通のリスト(メモリを全部持つ)

import sys

lst = list(range(100000))
print(f"リストのサイズ: {sys.getsizeof(lst)} bytes")  # → メモリ大量に使う

⚡ 次にジェネレーター的な range()

gen = range(100000)
print(f"rangeオブジェクトのサイズ: {sys.getsizeof(gen)} bytes")  # → 数十バイトしか使わない

✅ 結果まとめ

オブジェクト メモリサイズ(例)
list(range(100000)) 約 800,000 bytes以上
range(100000) 約 48 bytes

🧠 なぜこんなに違うの?

  • list全要素をメモリに一括で持つ
  • range()generator1つずつ「必要になったときに」値を生成(=遅延評価)

💡 補足:ジェネレーター関数の例

def my_gen():
    for i in range(3):
        yield i

g = my_gen()
print(next(g))  # → 0
print(next(g))  # → 1

🎉 まとめ

  • range()yield を使うと、メモリ効率がぐっと上がります
  • リスト化(list(range(...)))するかどうかで、メモリ使用量が桁違い
  • 大量データを扱うときこそジェネレーターの出番
1
0
1

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?