Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6232923
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T10:12:16+00:00 2026-05-24T10:12:16+00:00

i don’t get the full grasp on python iterators, i got an object with

  • 0

i don’t get the full grasp on python iterators,
i got an object with a list of children, and i want to iterate through this structure.
I want to get the same behaviour as with the printall function but with an iterator.

    class t:
            def __init__(self, i):
                    self.l = []
                    self.a = 0
                    for ii in range(i):
                            self.a = ii
                            self.l.append(t(i-1))

            def __iter__(self):
                    return self

            def next(self):
                    for i in self.l:
                            yield i.__iter__()
                    yield self

            def printall(self):
                    for i in self.l:
                            i.printall()
                    print self.a

hope thats enough information, thanks

edit:

i just want to be able to iterate through all the leafs of the tree and do something with the object, i.e. when i have an instance

    bla = t(3) 

i want to be able to go through every node with

    for x in bla:
            print x.a

for example. i want to be able to something with each x,
i just have to access every child once

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T10:12:17+00:00Added an answer on May 24, 2026 at 10:12 am

    It sounds like you want the iterator to act as a tree traversal. Study the itertools module and you can really go places.

    from itertools import chain, imap
    
    class t:
      def __init__(self, value):
        self.value = value
        self.children = []
      def __iter__(self):
        "implement the iterator protocol"
        for v in chain(*imap(iter, self.children)):
          yield v
        yield self.value
    
    root = t(0)
    root.children.append(t(1))
    root.children.append(t(2))
    root.children[1].children.append(t(3))
    print list(iter(root))   # -> [1, 3, 2, 0]
    print list(iter(root.children[1]))  # -> [3, 2]
    

    EDIT: Below is the originally accepted implementation. It has a performance problem; I would remove it, but it seems wrong to remove content that was an accepted answer. It will fully traverse the entire structure, creating O(N*log[M](N)) generator objects (for a balanced tree with branching factor M containing N total elements), before yielding any values. But it does produce the desired result with a simple expression.

    (The above implementation visits areas of the tree on demand and has only O(M+log[M](N)) generator objects in memory at a time. In both implementations, only O(log[M](N)) levels of nested generators are expected.)

    from itertools import chain
    
    def isingle(item):
      "iterator that yields only a single value then stops, for chaining"
      yield item
    
    class t:
      # copy __init__ from above
      def __iter__(self):
        "implement the iterator protocol"
        return chain(*(map(iter, self.children) + [isingle(self.value)]))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Don't want to sort the entries. using this does not preserve the order as
I don't know if i am doing it right, this is what I got:
Don't get me wrong, I want them to get saved. But I always thought
Don't dismiss this as a newbie question! It's not, I'm not, I've tried everything,
I don't understand where the extra bits are coming from in this article about
I don't want PHP errors to display /html, but I want them to display
Don't know if there is a better way to do this, so that is
Don't think this is a repost, difficult to search for the word between because
Don't need to do this right now but thinking about the future... What would
I don't know Regex very well, and I'm trying to get all of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.