<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>iterators</title>
	<atom:link href="https://techgrowup.net/tag/iterators/feed/" rel="self" type="application/rss+xml" />
	<link>https://techgrowup.net</link>
	<description>エンジニアを強くする</description>
	<lastBuildDate>Thu, 21 Nov 2024 05:59:47 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1</generator>

<image>
	<url>https://techgrowup.net/wp-content/uploads/2021/05/hp-icon-150x150.png</url>
	<title>iterators</title>
	<link>https://techgrowup.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Python開発入門17 Pythonイテレータの基本と応用</title>
		<link>https://techgrowup.net/python-iterators/</link>
					<comments>https://techgrowup.net/python-iterators/?noamp=mobile#respond</comments>
		
		<dc:creator><![CDATA[techgrowup]]></dc:creator>
		<pubDate>Thu, 21 Nov 2024 05:59:44 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[iterators]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://techgrowup.net/?p=2114</guid>

					<description><![CDATA[はじめに Pythonの「イテレータ」とは、データを順番に処理するための仕組みを提供する、Pythonの中心的な概念の一つです。リストやタプルのようなコレクション型データを効率よく扱うために、イテレータは非常に重要です。 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h1 class="wp-block-heading">は<strong>じめに</strong></h1>



<p class="wp-block-paragraph">Pythonの「イテレータ」とは、データを順番に処理するための仕組みを提供する、Pythonの中心的な概念の一つです。リストやタプルのようなコレクション型データを効率よく扱うために、イテレータは非常に重要です。</p>



<p class="wp-block-paragraph">この記事では、Pythonのイテレータについて、以下の内容を詳しく解説します：</p>



<ul class="wp-block-list">
<li>イテレータの基本概念と動作原理</li>



<li>実践的な使い方</li>



<li>独自イテレータの作成方法</li>



<li>よくあるエラーとその対処法</li>
</ul>



<p class="wp-block-paragraph">初心者でも理解しやすいように、具体例を交えながら解説します。</p>



<h2 class="wp-block-heading"><strong>Pythonイテレータとは</strong></h2>



<h3 class="wp-block-heading"><strong>イテレータの基本概念</strong></h3>



<p class="wp-block-paragraph">Pythonのイテレータは、データを1つずつ順番に取り出すためのオブジェクトです。イテレータには次の2つの重要なメソッドがあります：</p>



<ul class="wp-block-list">
<li><strong><code>__iter__()</code></strong>: イテレータオブジェクト自身を返します。</li>



<li><strong><code>__next__()</code></strong>: コレクションから次の要素を返します。</li>
</ul>



<p class="wp-block-paragraph">イテレータを使うことで、ループ処理を効率的に行えます。</p>



<h3 class="wp-block-heading"><strong>イテレータの仕組み</strong></h3>



<p class="wp-block-paragraph">Pythonでは、リスト、タプル、文字列などの「反復可能なオブジェクト（Iterable）」は、自動的にイテレータとして扱えます。<br>例を見てみましょう：</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="my_list = [1, 2, 3]
my_iter = iter(my_list)

print(next(my_iter))  # 出力: 1
print(next(my_iter))  # 出力: 2
print(next(my_iter))  # 出力: 3" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">my_list = [</span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">3</span><span style="color: #D4D4D4">]</span></span>
<span class="line"><span style="color: #D4D4D4">my_iter = </span><span style="color: #DCDCAA">iter</span><span style="color: #D4D4D4">(my_list)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #DCDCAA">next</span><span style="color: #D4D4D4">(my_iter))  </span><span style="color: #6A9955"># 出力: 1</span></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #DCDCAA">next</span><span style="color: #D4D4D4">(my_iter))  </span><span style="color: #6A9955"># 出力: 2</span></span>
<span class="line"><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #DCDCAA">next</span><span style="color: #D4D4D4">(my_iter))  </span><span style="color: #6A9955"># 出力: 3</span></span></code></pre></div>



<p class="wp-block-paragraph">ここでは、<code>iter()</code>を使ってリストをイテレータに変換し、<code>next()</code>を使って要素を順番に取り出しています。</p>



<h2 class="wp-block-heading"><strong>Pythonのイテレータを使う方法</strong></h2>



<h3 class="wp-block-heading"><strong><code>for</code>ループとイテレータ</strong></h3>



<p class="wp-block-paragraph">Pythonの<code>for</code>ループは、内部的にイテレータを利用して動作します。以下のコードは、リストをイテレータで処理する例です：</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="my_list = [1, 2, 3]
for item in my_list:
    print(item)" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">my_list = [</span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">3</span><span style="color: #D4D4D4">]</span></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> item </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> my_list:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(item)</span></span></code></pre></div>



<p class="wp-block-paragraph">これは、次のようなイテレータを直接使ったコードと同等です：</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="my_list = [1, 2, 3]
my_iter = iter(my_list)

while True:
    try:
        item = next(my_iter)
        print(item)
    except StopIteration:
        break" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">my_list = [</span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">3</span><span style="color: #D4D4D4">]</span></span>
<span class="line"><span style="color: #D4D4D4">my_iter = </span><span style="color: #DCDCAA">iter</span><span style="color: #D4D4D4">(my_list)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">while</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">True</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">try</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        item = </span><span style="color: #DCDCAA">next</span><span style="color: #D4D4D4">(my_iter)</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(item)</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">except</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">StopIteration</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">break</span></span></code></pre></div>



<h3 class="wp-block-heading"><strong>イテレータの停止</strong></h3>



<p class="wp-block-paragraph">イテレータは要素が尽きると<code>StopIteration</code>例外をスローします。通常、<code>for</code>ループはこの例外を内部で処理するため、ユーザーが意識する必要はありません。</p>



<h3 class="wp-block-heading"><strong>イテラブルオブジェクトとイテレータの違い</strong></h3>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th><strong>イテラブル（Iterable）</strong></th><th><strong>イテレータ（Iterator）</strong></th></tr></thead><tbody><tr><td>データを保持するオブジェクト</td><td>データを順番に返すオブジェクト</td></tr><tr><td>例: リスト、タプル、文字列</td><td>例: <code>iter()</code>で作成したオブジェクト</td></tr></tbody></table></div></figure>



<h2 class="wp-block-heading"><strong>独自イテレータの作成方法</strong></h2>



<p class="wp-block-paragraph">Pythonでは、独自のイテレータをクラスとして作成することが可能です。以下に簡単な例を示します。</p>



<h3 class="wp-block-heading"><strong>独自イテレータの例</strong></h3>



<p class="wp-block-paragraph">以下のコードは、1から10までの数を返す独自イテレータの例です：</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="class MyIterator:
    def __init__(self):
        self.current = 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.current &lt;= 10:
            value = self.current
            self.current += 1
            return value
        else:
            raise StopIteration

my_iter = MyIterator()

for num in my_iter:
    print(num)" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">class</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">MyIterator</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">__init__</span><span style="color: #D4D4D4">(</span><span style="color: #9CDCFE">self</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #569CD6">self</span><span style="color: #D4D4D4">.current = </span><span style="color: #B5CEA8">1</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">__iter__</span><span style="color: #D4D4D4">(</span><span style="color: #9CDCFE">self</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">return</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">self</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">__next__</span><span style="color: #D4D4D4">(</span><span style="color: #9CDCFE">self</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">if</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">self</span><span style="color: #D4D4D4">.current &lt;= </span><span style="color: #B5CEA8">10</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">            value = </span><span style="color: #569CD6">self</span><span style="color: #D4D4D4">.current</span></span>
<span class="line"><span style="color: #D4D4D4">            </span><span style="color: #569CD6">self</span><span style="color: #D4D4D4">.current += </span><span style="color: #B5CEA8">1</span></span>
<span class="line"><span style="color: #D4D4D4">            </span><span style="color: #C586C0">return</span><span style="color: #D4D4D4"> value</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">else</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">            </span><span style="color: #C586C0">raise</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">StopIteration</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">my_iter = MyIterator()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> num </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> my_iter:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(num)</span></span></code></pre></div>



<p class="wp-block-paragraph"><strong>出力:</strong></p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="1
2
3
4
5
6
7
8
9
10" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #B5CEA8">1</span></span>
<span class="line"><span style="color: #B5CEA8">2</span></span>
<span class="line"><span style="color: #B5CEA8">3</span></span>
<span class="line"><span style="color: #B5CEA8">4</span></span>
<span class="line"><span style="color: #B5CEA8">5</span></span>
<span class="line"><span style="color: #B5CEA8">6</span></span>
<span class="line"><span style="color: #B5CEA8">7</span></span>
<span class="line"><span style="color: #B5CEA8">8</span></span>
<span class="line"><span style="color: #B5CEA8">9</span></span>
<span class="line"><span style="color: #B5CEA8">10</span></span></code></pre></div>



<h2 class="wp-block-heading"><strong>イテレータとジェネレータの比較</strong></h2>



<p class="wp-block-paragraph">Pythonには「ジェネレータ」と呼ばれる、イテレータに似た機能があります。以下の表で違いを見てみましょう。</p>



<figure class="wp-block-table"><div class="scrollable-table"><table class="has-fixed-layout"><thead><tr><th><strong>イテレータ</strong></th><th><strong>ジェネレータ</strong></th></tr></thead><tbody><tr><td>明示的に<code>__iter__()</code>と<code>__next__()</code>を定義</td><td><code>yield</code>キーワードで簡単に作成可能</td></tr><tr><td>メモリを多く消費する場合がある</td><td>必要なデータだけを生成するため効率的</td></tr></tbody></table></div></figure>



<h3 class="wp-block-heading"><strong>ジェネレータの例</strong></h3>



<p class="wp-block-paragraph">以下のジェネレータは、1から10までの数を返します：</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="def my_generator():
    for i in range(1, 11):
        yield i

for num in my_generator():
    print(num)" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">my_generator</span><span style="color: #D4D4D4">():</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> i </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">11</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">yield</span><span style="color: #D4D4D4"> i</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> num </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> my_generator():</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(num)</span></span></code></pre></div>



<p class="wp-block-paragraph">ジェネレータは、複雑なイテレータをシンプルに記述できるため、実務で頻繁に利用されます。</p>



<h2 class="wp-block-heading"><strong>イテレータのメリットとデメリット</strong></h2>



<h3 class="wp-block-heading"><strong>メリット</strong></h3>



<ol class="wp-block-list">
<li><strong>効率的なメモリ使用</strong>: 必要なデータだけを順次処理するため、大量データを扱う際に有効。</li>



<li><strong>柔軟性</strong>: 独自のロジックを組み込んだデータ処理が可能。</li>



<li><strong>簡潔なコード</strong>: <code>for</code>ループなどで簡潔に操作可能。</li>
</ol>



<h3 class="wp-block-heading"><strong>デメリット</strong></h3>



<ol class="wp-block-list">
<li><strong>再利用性の低さ</strong>: イテレータは一度消費すると再利用できません。</li>



<li><strong>デバッグの難しさ</strong>: データ処理の流れを追跡するのが難しい場合がある。</li>
</ol>



<h2 class="wp-block-heading"><strong>よくあるエラーとその対処法</strong></h2>



<h3 class="wp-block-heading"><strong><code>StopIteration</code>の処理</strong></h3>



<p class="wp-block-paragraph"><code>StopIteration</code>は、イテレータの要素が尽きたときに発生します。この例外は、通常<code>for</code>ループで自動処理されますが、手動で対処する場合は<code>try-except</code>を使います。</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="my_list = [1, 2, 3]
my_iter = iter(my_list)

while True:
    try:
        print(next(my_iter))
    except StopIteration:
        print(&quot;イテレータが終了しました&quot;)
        break" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">my_list = [</span><span style="color: #B5CEA8">1</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">2</span><span style="color: #D4D4D4">, </span><span style="color: #B5CEA8">3</span><span style="color: #D4D4D4">]</span></span>
<span class="line"><span style="color: #D4D4D4">my_iter = </span><span style="color: #DCDCAA">iter</span><span style="color: #D4D4D4">(my_list)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">while</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">True</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">try</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #DCDCAA">next</span><span style="color: #D4D4D4">(my_iter))</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">except</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">StopIteration</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;イテレータが終了しました&quot;</span><span style="color: #D4D4D4">)</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">break</span></span></code></pre></div>



<h2 class="wp-block-heading"><strong>まとめ</strong></h2>



<p class="wp-block-paragraph">Pythonのイテレータは、データを効率的に処理するための強力なツールです。リストやタプルなどのコレクション型データの操作に欠かせないだけでなく、独自イテレータを作成することで柔軟なデータ操作が可能になります。また、ジェネレータを利用することで、より簡潔で効率的なデータ処理が実現します。</p>



<p class="wp-block-paragraph">イテレータを正しく理解し、活用することで、Pythonプログラミングの幅が広がるでしょう。TechGrowUpでは、Pythonのさらなる知識を深めるための役立つ情報を提供しています。ぜひ他の記事もご覧ください！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://techgrowup.net/python-iterators/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
