9cubed
ブログ | Tailwind | Vite | Python | Node.js | Linux | PowerShell | その他 | 将棋ウォーズ | 歌の練習
< 前の記事

Python - 名前空間パッケージのインポート(import)

次の記事 >

Python - map

Python

Python - yield

公開日:2019-03-12
更新日:2019-05-29

1. 概要

yield の使い方です。
通常関数は return で処理を抜けますが、yield でも処理を抜けることができます。
yield を使って抜けた場合、次回は yield の次の行から処理が始まります。
これを利用して、論理的なリストのようなものを作成することができます。

2. 動画



3. サンプル

yield の動作確認のためのサンプルです。

def no_list():
	yield 1
	yield 2
	yield 3
	yield 4
	yield 5

for no in no_list():
	print(no)

1
2
3
4
5

上記の no_list() は、以下のようにも書けます。
def no_list():
	for no in [1,2,3,4,5]:
		yield no

4. ジェネレーターについて

yield を含む関数は、戻り値としてジェネレーター(generator)を返します。
ジェネレーターの __next__() を実行すると、yield まで処理が実行され、yield に指定された値が返ります。
再度 __next__() を実行すると、前回の yield の次の行から処理が再開されます。

def no_list():
	yield 1
	yield 2
	yield 3
	yield 4
	yield 5

g = no_list()

print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(g.__next__())

print (type(no_list))
print (type(g))

1
2
3
4
5
<class 'function'>
<class 'generator'>

5. range() の実装

1つずつ増える range() を実装してみます。

def my_range(start_no, end_no):
	no = start_no
	while end_no > no:
		yield no
	no = no + 1


for no in my_range(1, 6):
	print(no)

print("-----")

for no in range(1, 6):
	print(no)
1
2
3
4
5
-----
1
2
3
4
5


< 前の記事

Python - 名前空間パッケージのインポート(import)

次の記事 >

Python - map

YouTube X

新着一覧

  • SCSS のインストールVite
  • Tailwind CSS のプロジェクトの作成Tailwind
  • TypeScriptのプロジェクトの作成Vite
  • Flask のインストールと動作確認Python
  • 簡易Webサーバーの作成Python
  • pipeline で文章の生成Python
  • pipeline で文章の要約Python
  • 音声から文字起こしPython
  • Node.js のインストールNode.js
  • .ps1(PowerShellスクリプト)を実行可能にするPowerShell

アーカイブ

  • 2025/12
  • 2025/11
  • 2025/10
  • 2025/09
  • 2025/08

以前のカテゴリー一覧

  • CakePHP3
  • CentOS7
  • HTML・CSS・JavaScript
  • Haskell
  • JavaScript
  • Kotlin
  • Laravel5
  • PHP
  • Python
  • Ruby
  • RubyOnRails5
  • TypeScript
  • Vue.js
  • Webサーバ講座
  • Webプログラミング講座
  • jQuery
  • linux
  • パソコン講座
  • ブログ
  • プログラミング講座
  • メモ帳作成講座
  • 数学

Copyright © 9cubed. All Rights Reserved.

プライバシーポリシー 利用規約
▲