I'm a newer to Python and I'm learning it.
Here I want to use a generator to output the Pascal's Triangle. I'd like to get the output like this
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
And what I wrote is
# Pascal's Triangle
def triangles() :
result = [1]
while True :
# if i use yield result, the output will be [1, 0], [1, 1, 0] ...
yield result[:]
result.append(0)
result = [result[i]+result[i-1] for i in range(len(result))]
# make a list of the triangles.
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 5:
break
for t in results:
print(t)
This code works well. However when I change yield result[:]
to yield result
, the output is
[1, 0]
[1, 1, 0]
[1, 2, 1, 0]
[1, 3, 3, 1, 0]
[1, 4, 6, 4, 1]
After debugging the code, I found that the iteration variable t
changed to [1, 0]
after running
result.append(0)
the first time, but there isn't any words like return
or yield
.
Why could that happen?
Update Question
I made a minimal working example here
def func():
a = [1, 2]
while True :
yield a
a.append(0)
# # PM 1 (Print Method 1)
# n = 0
# results = []
# b = func()
# for t in b:
# results.append(t)
# n = n + 1
# if n == 3:
# break
# for t in results:
# print(t)
# PM 2
b = func()
counter = 0
for i in b :
print(i)
counter += 1
if counter == 3:
break
When I use PM 1
to print the list, I got
[1, 2, 0, 0]
[1, 2, 0, 0]
[1, 2, 0, 0]
When I use PM 2
to print the list, I got
[1, 2]
[1, 2, 0]
[1, 2, 0, 0]
So I think the problem occurs at how I print the list.