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項目

6章内包表記とジェネレータ

大半のプログラムは、リストや辞書、集合などのデータ構造とその処理からなります。Pythonにはそれらのデータ構造に対する反復処理や派生的なデータを簡潔に生成する特殊な構文である内包表記があります。内包表記にはコードの可読性が大幅に向上するなどの利点が多くあります。

内包表記はジェネレータに拡張されます。ジェネレータはforループや*argsによるアンパックなど、イテレータが使える場所ならばどこでも利用できます。ジェネレータを使えば、コードのパフォーマンス向上、メモリ使用量の削減、可読性の向上、実装の簡略化が実現できます。

項目40 mapやfilterの代わりに内包表記を使う

Pythonにはシーケンスやイテラブルオブジェクトから新しいリストを生成するコンパクトな構文があります。それはリスト内包表記と呼ばれます。例えば、リストの各要素の二乗を計算したいとします。まず、単純なforループで計算します。

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = []
for x in a:
    squares.append(x**2)
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

リスト内包表記を使えば、計算式とループ対象のイテラブルオブジェクトを指定するだけで、同じ結果を1行で実現できます。

squares = [x**2 for x in a]  # リスト内包表記
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

単一引数を受け取る関数を適用する場合を除いて、リスト内包表記は単純なケースでは組み込み関数 ...

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