Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
yield question with append
#1
when I try to use print the output the yield result, everything is shown as expected. The code and output is as below:
def triangles():
    oo = [1] 
    yield oo 
    oo.append(1)
    yield oo  
    oo.append(1)
    yield oo 
    oo.append(1)
    yield oo 

# Collect the first 3 rows of Triangle
n = 0
for t in triangles():
    print (t)
    n += 1
    if n == 3:  
        break
the output is:
Output:
[1] [1, 1] [1, 1, 1]
However when I tried to append the yield result further, like below
n = 0
results = []
for t in triangles():
    ## print (t)
    results.append(t)
    n += 1
    if n == 3:  
        break

# Print the results
for t in results:
    print(t)
the output becomes:
Output:
[1, 1, 1] [1, 1, 1] [1, 1, 1]
Actually it is hard for me to understand the result. why the 1st and 2nd row changes after further appending?
Reply


Messages In This Thread
yield question with append - by gnomegordon - Dec-04-2024, 05:44 PM
RE: yield question with append - by deanhystad - Dec-04-2024, 06:29 PM
RE: yield question with append - by gnomegordon - Dec-04-2024, 06:47 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  yield from akbarza 4 1,926 Apr-19-2024, 07:58 PM
Last Post: DeaD_EyE
  yield usage as statement or expression akbarza 5 2,222 Oct-23-2023, 11:43 AM
Last Post: Gribouillis
  Using list comprehension with 'yield' in function tester_V 5 3,948 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Yield generator weird output Vidar567 8 5,259 Nov-23-2020, 10:59 PM
Last Post: deanhystad
  Trying to access next element using Generator(yield) in a Class omm 2 2,882 Oct-19-2020, 03:36 PM
Last Post: omm
  Yield statement question DPaul 6 3,756 Sep-26-2020, 05:18 PM
Last Post: DPaul
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 4,397 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  Problem about yield, please help!! cls0724 5 4,284 Apr-08-2020, 05:37 PM
Last Post: deanhystad
  does yield support variable args? Skaperen 0 2,144 Mar-03-2020, 02:44 AM
Last Post: Skaperen
  generator function that yield from a list buran 9 6,094 Jun-04-2019, 10:26 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020