1
3

More than 3 years have passed since last update.

Python タプルの内包表記とジェネレータ式

Last updated at Posted at 2020-05-09
1 / 2

タプルの内包表記とジェネレータ式の違いについてメモを残しておきます

まずは内包表記の復習から///

inner.py
list=[]
for x in range(10):
    list.append(x)
print(list)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


#これを内包表記に書き換えると

list2=[x for x in range(10)]
print(list2)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


では本題のタプルの内包表記とジェネレータ式について

tuple.py
#普通のイテレータ
def g():
    for i in range(4):
        yield i
g=g()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
"""
0
1
2
3
"""


g=(i for i in range(4))#タプルのように思えるがジェネレーターである
print(type(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
"""
<class 'generator'>
0
1
2
3

"""







iterator.py
g=tuple(i for i in range(4))#タプルの場合は括弧の前にtupleと記述する必要あり
print(type(g))
print(g)
#<class 'tuple'>
#(0, 1, 2, 3)

まとめ

ジェネレータ式では()内に記述すればいいのに対し、

タプルの内包表記では()の前にtupleと記述する必要があります。

1
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3