Home > front end >  The result of inline and usual for loops are different
The result of inline and usual for loops are different

Time:03-01

I have a tree which I want to return its children as a list through a function. In the function, I needed to iterate over a list of strings. At first I did it by using the inline foor loop

    def get_children(root):
        
        Data = [ ]
        Data.append( root.data )
        
        for child in root.children:
              Data.append( elem for elem in get_children(child) )
        return Data

however, I got the following strange result

['Electronics', <generator object get_children.<locals>.<genexpr> at 0x7fb3a081a3c0>, <generator object get_children.<locals>.<genexpr> at 0x7fb3a081a7b0>, <generator object get_children.<locals>.<genexpr> at 0x7fb3a081a9e0>]

Then, I changed the inline for loop into a typical one and the problem is resolved, i.e.,

   for elem in get_children(child):
        Data.append( elem )

I was wondering if you help me to understand why this happened. I've read a similar post about list comprehension, however, I still have confusion to understand the difference here.

CodePudding user response:

Because you didn't wrap your list comprehension with [], the return value of it is a generator expression (which generates the list you made). You can fix this by simply wrapping the expression with []

CodePudding user response:

you used Generator expressions instead of list comprehension Generator Expressions are somewhat similar to list comprehensions, but the former doesn’t construct list object. Instead of creating a list and keeping the whole sequence in the memory the generator generates the next element in demand.

CodePudding user response:

The problem is here at Data.append( elem for elem in get_children(child)), you haven't wrapped the list comprehension. So the solution is Data.append([elem for elem in get_children(child)]) to just add [ at start and ] at end of list comprehension.

I think yo are trying to get all child of the root, well here's solution from Getting every child widget of a Tkinter window

root.winfo_children()

You can use this instead of for-loop, as this would provide you with every children of root window.

  • Related