Pythonのimport collectionsの書き方|importできる9つの一覧と「cannot import name Iterable」の直し方
Pythonのcollectionsは標準ライブラリなので、インストールせずにimport collectionsまたはfrom collections import Counterのように書くだけで使えます。importできるのはCounter・defaultdict・deque・namedtuple・OrderedDict・ChainMap・UserDict・UserList・UserStringの9つで、IterableやMappingなどの抽象基底クラスはPython 3.10以降from collections.abc import Iterableと書く必要があります。
この記事では、collectionsのimportの書き方と、importできる9つの名前の早見表、そして「cannot import name 'Iterable' from 'collections'」など、import時によく出るエラーの原因と直し方を実行結果つきで解説します。コードはPython 3.12で実行し、仕様はPython公式ドキュメント(collections)とcollections.abcで確認しました(2026年10月18日確認、ドキュメントはPython 3.15.0版)。各クラスのメソッドは「Python collectionsのメソッド一覧」で詳しく扱っています。
import collectionsの書き方は2通り
import collections
c = collections.Counter("banana")
print(c)
from collections import Counter, defaultdict, deque
print(Counter("banana").most_common(1))
d = defaultdict(list)
d["fruit"].append("apple")
print(dict(d))
q = deque([1, 2, 3], maxlen=3)
q.append(4)
print(q)
実行結果:
Counter({'a': 3, 'n': 2, 'b': 1})
[('a', 3)]
{'fruit': ['apple']}
deque([2, 3, 4], maxlen=3)
| 書き方 | 使うときの書き方 | 向いている場面 |
|---|---|---|
import collections |
collections.Counter(...) |
どこから来た名前か一目でわかる。使う回数が少ない |
from collections import Counter |
Counter(...) |
何度も使う。コードを短くしたい(実務ではこちらが多い) |
どちらも動作は同じです。from collections import *のようなワイルドカードは、どの名前が入ってきたかわかりにくくなるので避けるのが無難です。
from collections importできる名前の一覧
collectionsモジュールが公開している名前(collections.__all__)を、Python 3.12で表示すると次の9つです。
import collections
print([n for n in collections.__all__])
実行結果:
['ChainMap', 'Counter', 'OrderedDict', 'UserDict', 'UserList', 'UserString', 'defaultdict', 'deque', 'namedtuple']
| import文 | 何をするものか(公式ドキュメントの説明) | よくある用途 |
|---|---|---|
from collections import Counter |
ハッシュ可能なオブジェクトを数えるdictのサブクラス | 出現回数の集計、多い順の取り出し |
from collections import defaultdict |
無いキーの値を関数で補うdictのサブクラス | グループ分け、KeyErrorを出さない集計 |
from collections import deque |
両端での追加・取り出しが速いリストに似たコンテナ | キュー、直近n件だけ残す |
from collections import namedtuple |
名前付きフィールドを持つタプルのサブクラスを作る関数 | 座標やレコードを読みやすく扱う |
from collections import OrderedDict |
要素を追加した順番を覚えるdictのサブクラス | 順番の入れ替え(move_to_end) |
from collections import ChainMap |
複数の辞書を1つに見せるdictに似たクラス | 設定の優先順位(利用者設定→既定値) |
from collections import UserDict |
dictを継承しやすくするラッパー | 独自の辞書クラスを作る |
from collections import UserList |
listを継承しやすくするラッパー | 独自のリストクラスを作る |
from collections import UserString |
strを継承しやすくするラッパー | 独自の文字列クラスを作る |
このうち関数はnamedtuple()だけで、残りはクラスです。よく使う3つ(Counter・defaultdict・deque)以外の例も見ておきます。
from collections import namedtuple, OrderedDict, ChainMap
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p, p.x + p.y)
od = OrderedDict(a=1, b=2, c=3)
od.move_to_end("a")
print(list(od))
defaults = {"color": "red", "size": "M"}
user = {"size": "L"}
print(ChainMap(user, defaults)["size"], ChainMap(user, defaults)["color"])
実行結果:
Point(x=3, y=4) 7
['b', 'c', 'a']
L red
個別の使い方は「Counterの使い方」「defaultdictとは?」「dequeの使い方」「namedtupleとは?」の各記事で解説しています。
ImportError: cannot import name ‘Iterable’ from ‘collections’ の直し方
古いコードやライブラリを動かすと、次のエラーが出ることがあります。
try:
from collections import Iterable
except ImportError as e:
print("ImportError:", e)
実行結果(パスは環境によって変わります):
ImportError: cannot import name 'Iterable' from 'collections' (.../lib/python3.12/collections/__init__.py)
IterableやMapping、Sequence、Callableなどの抽象基底クラス(ABC)は、Python 3.3でcollections.abcに移りました。しばらくはcollectionsからも読み込めましたが、Python 3.10の変更点(What’s New)に「collectionsモジュールから、抽象基底クラスへの非推奨の別名を削除した」と書かれているとおり、3.10以降はエラーになります(2026年10月18日確認)。
直し方は、importをcollections.abcに書き換えるだけです。
from collections.abc import Iterable, Mapping, Sequence
for obj in [[1, 2], "abc", {"a": 1}, 10, (x for x in range(3))]:
print(type(obj).__name__, isinstance(obj, Iterable), isinstance(obj, Mapping), isinstance(obj, Sequence))
実行結果:
list True False True
str True False True
dict True True False
int False False False
generator True False False
自分のコードではなく、インストールしたライブラリの中でこのエラーが出ている場合は、そのライブラリが古いのが原因です。pip install -U ライブラリ名で新しい版に更新すると直ることが多く、ライブラリのファイルを直接書き換えるのはおすすめしません。import時のエラー全般の読み方は「ImportError: cannot import name ‘X’ from ‘Y’ の原因と直し方」で解説しています。
collections.abcでimportできる主な名前
| 名前 | isinstanceで調べられること |
|---|---|
Iterable |
for文で回せるか(__iter__を持つか) |
Iterator |
イテレータか(__next__も持つか) |
Sequence/MutableSequence |
リストやタプルのように番号で取り出せるか/書き換えられるか |
Mapping/MutableMapping |
辞書のようにキーで取り出せるか/書き換えられるか |
Set/MutableSet |
集合として振る舞うか |
Callable |
関数のように呼び出せるか |
Hashable/Sized/Container |
ハッシュ可能か/len()が使えるか/inが使えるか |
公式ドキュメントでは、ほかにGeneratorやAwaitable、Bufferなども定義されています。自分で抽象基底クラスを作る方法は「Pythonのabc(抽象基底クラス)の使い方」を参照してください。
型ヒントでもcollections.abcを使う
Python 3.9以降、collections.abcのクラスはIterable[int]のように[]で型を指定できるようになり、typingのドキュメントではtyping.Iterableなどは「collections.abcの非推奨の別名」とされています(2026年10月18日確認)。新しく書く型ヒントはcollections.abcから読み込みます。
from collections.abc import Iterable
def total(values: Iterable[int]) -> int:
return sum(values)
print(total([1, 2, 3]), total(range(4)), total({5, 6}))
実行結果:
6 6 11
型ヒントの書き方全般は「Pythonの型ヒントでlist・dict・tupleを書く方法」でまとめています。
import collectionsだけではcollections.abcが使えないことがある
collections.abcは、collectionsの中にある別のモジュール(サブモジュール)です。import collectionsと書いただけでは読み込まれないため、次のようにAttributeErrorになることがあります。
import collections
try:
print(collections.abc.Iterable)
except AttributeError as e:
print("AttributeError:", e)
import collections.abc
print(collections.abc.Iterable)
実行結果:
AttributeError: module 'collections' has no attribute 'abc'
<class 'collections.abc.Iterable'>
やっかいなのは、ほかのモジュール(たとえばtyping)が先にcollections.abcを読み込んでいると、import collectionsだけでも動いてしまう点です。Python 3.12でimport typing, collectionsとしてからcollections.abc.Iterableを使うと、エラーになりませんでした。たまたま動いているコードが、importの順番を変えただけで壊れることがあるので、collections.abcを使うときはimport collections.abcかfrom collections.abc import ...と明示しましょう。
collectionsのimportでよくある間違い
for stmt in ["from collections import heapq", "from collections import list", "from collections import counter"]:
try:
exec(stmt)
except ImportError as e:
print(stmt, "->", e)
import heapq
print(heapq.nsmallest(2, [5, 1, 4, 2]))
実行結果(パスは省略):
from collections import heapq -> cannot import name 'heapq' from 'collections' (...)
from collections import list -> cannot import name 'list' from 'collections' (...)
from collections import counter -> cannot import name 'counter' from 'collections' (...)
[1, 2]
| 間違い | 原因 | 正しい書き方 |
|---|---|---|
from collections import heapq |
heapqはcollectionsとは別の標準モジュール | import heapq |
from collections import list |
list・dict・tupleは組み込み型で、importは不要 | そのままlist()を使う |
from collections import counter |
名前の大文字・小文字が違う | from collections import Counter |
from collections import Iterable |
3.10でcollections.abcへの別名が削除された | from collections.abc import Iterable |
pip install collections |
標準ライブラリなのでインストール不要 | 何もせずimportする |
なお、自分のファイルにcollections.pyという名前を付けると、標準ライブラリの代わりにそのファイルが読み込まれてしまい、同じような「cannot import name」エラーの原因になります。Python 3.12で試すと、同じフォルダにcollections.pyを置いた状態でfrom collections import Counterを実行したところ、そのファイルを指すImportErrorになりました。ファイル名は標準モジュールと重ならないようにしましょう。
importのエラーは、メッセージの読み方さえわかれば自分で直せるようになります。テックジムは対面・通学型のプログラミングスクールで、東京本校(永田町)などで自分のペースで学び、詰まったところはトレーナーに質問できます。毎週土曜には東京本校で無料Python講座(ゼロからはじめるPython入門講座)も開いています。
よくある質問
Q. Pythonのcollectionsはインストールが必要ですか?
不要です。collectionsはPythonに最初から入っている標準ライブラリなので、import collections や from collections import Counter と書くだけで使えます。pip install collections は必要ありません。
Q. from collections import Iterable でエラーになります。
Python 3.10でcollectionsモジュールから抽象基底クラスへの別名が削除されたためです。from collections.abc import Iterable に書き換えてください。ライブラリの中で出ている場合は、そのライブラリを新しい版に更新します。
Q. import collections と from collections import Counter はどちらがよいですか?
動作は同じです。何度も使うなら from collections import Counter のほうが短く書けます。どのモジュールの名前か明確にしたいときは import collections として collections.Counter と書きます。
Q. collectionsからimportできるものは何ですか?
Counter、defaultdict、deque、namedtuple、OrderedDict、ChainMap、UserDict、UserList、UserStringの9つです。IterableやMappingなどの抽象基底クラスはcollections.abcからimportします。
まとめ
- collectionsは標準ライブラリ。
import collectionsかfrom collections import Counterで使う - importできるのはCounter・defaultdict・deque・namedtuple・OrderedDict・ChainMap・UserDict・UserList・UserStringの9つ
- Iterable・Mappingなどは
collections.abcから。from collections import Iterableは3.10以降エラー collections.abcを使うときはimport collections.abcと明示する- heapqは別モジュール、listは組み込み型でimport不要
collectionsの関連記事
- Python Counterとは?要素の出現回数を数える使い方を徹底解説
- Python Counter.most_common()とは?多い順に取り出す方法
- Python defaultdictとは?キーがなくてもエラーにしない辞書の使い方
- Pythonのdequeでキュー・スタック・両端キューを効率的に扱う方法
- Python deque.append()とは?末尾に要素を追加する方法
- Python deque.popleft()とは?先頭から取り出す方法
- 【Python入門】namedtupleとは?使い方とメリットを初心者向けにわかりやすく解説
- Python順序付き辞書OrderedDictの使い方完全ガイド:挿入順序を保持する辞書操作テクニック
- Python ChainMapとは?複数の辞書を重ねて扱う方法を解説
- Python collections クラス一覧|Counter・defaultdict・dequeなどの使い方
collections の関連記事
collectionsモジュールはメソッド一覧・メンバー一覧の視点でも整理しています。あわせて読むと、どの名前がどの分類にあたるのかを把握しやすくなります。



