Python Forum
Problem about yield, please help!!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem about yield, please help!!
#1
I am still new to Python and i come across the below sample from my textbook that confuses me quite a lot.

[u]def flatten(nested, indent=""):
  try:
    print(indent, "Going to iterate over", nested)
    for sublist in nested:
      print(indent, "Going to iterate over flattening of",sublist)
      for element in flatten(sublist, indent+"  "):
        print(indent, "Yielding", element)
        yield element
  except TypeError:
    print(indent, "Type Error!  Yielding", nested)
    yield nested[/u]
The above code is to flatten a list. I understand how a list is flattened till you reach a number.
Then you reach Type Error.

However, i dun understand the next step when the
yield nested
then jump to
for element in flatten
.

I can comprehend the logic in between. I thought once you reached TypeError then it's the end of this loop. Why it will lead back to
for element in flatten
.

Thanks!
Reply


Messages In This Thread
Problem about yield, please help!! - by cls0724 - Apr-06-2020, 05:05 PM
RE: Problem about yield, please help!! - by cls0724 - Apr-07-2020, 04:42 PM
RE: Problem about yield, please help!! - by cls0724 - Apr-08-2020, 03:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  yield from akbarza 4 494 Apr-19-2024, 07:58 PM
Last Post: DeaD_EyE
  yield usage as statement or expression akbarza 5 991 Oct-23-2023, 11:43 AM
Last Post: Gribouillis
  Using list comprehension with 'yield' in function tester_V 5 1,399 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Yield generator weird output Vidar567 8 3,412 Nov-23-2020, 10:59 PM
Last Post: deanhystad
  Trying to access next element using Generator(yield) in a Class omm 2 2,081 Oct-19-2020, 03:36 PM
Last Post: omm
  Yield statement question DPaul 6 2,604 Sep-26-2020, 05:18 PM
Last Post: DPaul
  does yield support variable args? Skaperen 0 1,729 Mar-03-2020, 02:44 AM
Last Post: Skaperen
  generator function that yield from a list buran 9 4,393 Jun-04-2019, 10:26 PM
Last Post: snippsat
  yield help chakox 5 3,383 Apr-13-2019, 09:42 PM
Last Post: chakox
  Multiple calls to Python interpreter embedded in C++ application yield segmentation f mmoelle1 0 2,903 Mar-21-2019, 08:54 PM
Last Post: mmoelle1

Forum Jump:

User Panel Messages

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