Skip to Content
Effective Python 第3版 ―Pythonプログラムを改良する125項目
book

Effective Python 第3版 ―Pythonプログラムを改良する125項目

by Brett Slatkin, 鈴木 駿
October 2025
Intermediate to advanced
572 pages
7h 46m
Japanese
O'Reilly Japan, Inc.
Content preview from Effective Python 第3版 ―Pythonプログラムを改良する125項目

3章ループとイテレータ

プログラムでは固定長または可変長のシーケンスデータを処理することが多くあります。命令型プログラミング言語であるPythonならば、ループによるシーケンス処理が簡単に実装できます。ループ処理では一般的な、ループを実行するたびに変数やリスト、辞書に格納されたデータを読み込み、それに対応する状態の変更やI/O操作を行います。Pythonのループは組み込みのデータ型、コンテナ型、ユーザ定義クラスといった一般的なタスクに対して直感的に使えます。

また、Pythonはイテレータにも対応しており、データストリームを処理するために関数型の方法も使えます。つまり、シーケンスデータの構造を直接利用するのではなく、イテレータを介して抽象的にデータを扱います。イテレータを使うとプログラムが効率的になり、リファクタリングが容易になり、任意長のデータも処理できるようになります。Pythonにはイテレータを組み合わせて動作をカスタマイズできる機能も用意されています(詳細は「6章 内包表記とジェネレータ」参照)。

項目17 rangeよりenumerateを優先する

組み込み関数range()は整数値のシーケンスをイテレートする際に便利です。例えば、ランダムな32ビット値を生成することを考えます。

from random import randint

random_bits = 0
for i in range(32):
    if randint(0, 1):
        random_bits |= 1 << i

print(bin(random_bits))  # 0b11101000100100000111000010000001

文字列のリストのようなデータ構造をイテレートする場合は、シーケンスを直接イテレートできます。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Think Python 第3版 ―コンピュータ科学者の思考で問題を解決する

Think Python 第3版 ―コンピュータ科学者の思考で問題を解決する

Allen B. Downey, 大橋 真也
入門 Python 3 第2版

入門 Python 3 第2版

Bill Lubanovic, 鈴木 駿, 長尾 高弘

Publisher Resources

ISBN: 9784814401338Publisher Website