iter() イテレータを取得
最終更新:2026-09-22
iter() イテレータを取得
iter(obj) は obj のイテレータを返す;iter(callable, sentinel) は callable を sentinel が返されるまで繰り返し呼び出すイテレータを返す。
| カテゴリ | 組み込み関数 |
|---|---|
| 種類 | 組み込み関数 |
| Python バージョン | all |
📝 構文
iter(object[, sentinel])
⚙️ 引数
| object 必須 | An iterable; must be callable when sentinel is given. |
|---|---|
| sentinel 任意 | Sentinel: the callable is repeatedly called until it returns this value.(デフォルト値:None) |
戻り値:An iterator: obj's iterator, or a callable-driven iterator in the two-arg form.
💥 例外
TypeError— Raised when object is not iterable and no sentinel is given.
▶ 例
下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:
実行結果:
1 2
🏷️ 関連する組み込み関数
💡 関連するケース
さらに多くのケースは近日公開予定です。
❓ よくある質問
Qiter() と next() の関係は何ですか?
Aiter(obj) でイテレータを取得し、next(it) で要素を1つずつ取り出します。for ループは内部で iter() + next() の組み合わせです。
Q2引数形式の iter(func, sentinel) は何のためですか?
Afunc が sentinel を返すまで繰り返し呼び出し、返した時点で停止します。例:iter(lambda: input(), 'quit')。「終了マーカーまで読み込む」ような場面に最適です。
Qどのようなオブジェクトを iter() に渡せますか?
A__iter__ を実装したオブジェクト(list、dict、str、set など)や、シーケンスプロトコルの __getitem__ を持つオブジェクトです。整数のような普通のオブジェクトを渡すと TypeError になります。
Qiter() は遅延的ですか?
Aはい。iter() はイテレータを作るだけで実際の走査はしません。実際の値の生成は next() や for ループ実行時に行われます。