** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
def g():
for i in range(10):
yield i
g = g()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
result
<class 'generator'>
0
1
2
3
4
g = (i for i in range(10))
print(type(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
result
<class 'generator'>
0
1
2
3
4
At first glance it looks like a tuple, but if you just use ()
, it becomes a generator.
g = tuple(i for i in range(10))
print(type(g))
print(g)
result
<class 'tuple'>
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
You can generate tuples by prefixing ()
with tuple
.
Recommended Posts