Make a note about the difference between tuple comprehension and generator formula
First of all, from the review of the comprehension ///
inner.py
list=[]
for x in range(10):
list.append(x)
print(list)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#If you rewrite this as a comprehension
list2=[x for x in range(10)]
print(list2)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Now, about the tuple comprehension and generator formula of the main subject
tuple.py
#Ordinary iterator
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))#It sounds like a tuple, but it's a generator
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))#For tuples, you need to write tuple before the parentheses
print(type(g))
print(g)
#<class 'tuple'>
#(0, 1, 2, 3)
In the generator formula, it should be described in (), whereas it should be described in ().
In the tuple comprehension, you must write tuple before ().
Recommended Posts