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 7067783
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:14:37+00:00 2026-05-28T05:14:37+00:00

I’m trying to solve a problem that, unfortunately, goes beyond my capacity. I have

  • 0

I’m trying to solve a problem that, unfortunately, goes beyond my capacity.
I have a series of nested lists and while iterating over them, in case the next element is a list I want to append it as an attribute of my current element.
As usual, an example is better than my poor English (here’s some code to copy and paste):

class T(object):
    def __init__(self, id, children):
         self.id = id 
         self.children = children or []

    def __repr__(self):
         return u"T(id={0}, children={1})".format(self.id, self.children) 


# first a short example
l0 = [T(id=1, children=[]), T(id=2, children=[]), [T(id=3, children=[]), 
      T(id=4, children=[]), [T(id=5, children=[])]]]

As you can see l0 has 3 elements and the last one is list of three elements: what I need is to append the last list to the previous element that is not a list (and recursively)
Expected output:

l1 = magic(l0)    
[T(id=1, children=[]), T(id=2, children=[T(id=3, children=[]), T(id=4, children=[T(id=5, children=[])])])]

Hope somebody can share some advice to solve this, I’ve already invested a lot of hours and I’m not even close to solve it.

EDIT

For completeness, here’s a little more complex example

l0 = [T(children=[], id=1),
      T(children=[], id=2),
      T(children=[], id=3),
      [T(children=[], id=40),
       T(children=[], id=41),
       T(children=[], id=42),
       T(children=[], id=43),
       T(children=[], id=44),
       T(children=[], id=45),
       [T(children=[], id=50),
        T(children=[], id=51),
        T(children=[], id=52),
        T(children=[], id=54),
        [T(children=[], id=60),
         T(children=[], id=61),
         T(children=[], id=62),
         T(children=[], id=63),
         [T(children=[], id=70)],
         T(children=[], id=64)]]],
      T(children=[], id=8),
      T(children=[], id=9)]

I built a doctest using @rik-poggi function as example and so far it seems to be ok:

>>> from magic_bag import magic
>>> class T(object):                                                        
...     def __init__(self, id, children):                                   
...         self.id = id                                                    
...         self.children = children or []                                  
...                                                                         
...     def __repr__(self):                                                 
...         return u"T(children={0}, id={1})".format(self.children, self.id)
...                                                                         
>>> l0 = [T(id=1, children=[]), T(id=2, children=[]), T(id=3, children=[]), 
... [T(id=40, children=[]), T(id=41, children=[]), T(id=42, children=[]),   
... T(id=43, children=[]), T(id=44, children=[]), T(id=45, children=[]),    
... [T(id=50, children=[]), T(id=51, children=[]), T(id=52, children=[]),   
... T(id=54, children=[]), [T(id=60, children=[]), T(id=61, children=[]),   
... T(id=62, children=[]), T(id=63, children=[])]]], T(id=8, children=[]),  
... T(id=9, children=[])]                                                   
>>> l1 = magic(l0)                                              
>>> l1[0]                                                                   
T(children=[], id=1)                                                        
>>> l1[1]                                                                   
T(children=[], id=2)                                                        
>>> l1[3]                                                                   
T(children=[], id=8)                                                        
>>> l1[4]                                                                   
T(children=[], id=9)                                                        
>>> l1[5]                                                                   
Traceback (most recent call last):                                          
    ...                                                                     
IndexError: list index out of range                                         
>>> l1[2].children[5].children[3]                                           
T(children=[T(children=[], id=60), T(children=[], id=61), T(children=[], id=62), T(children=[], id=63)], id=54)
>>> l0 = [T(id=1, children=[]), T(id=2, children=[]), T(id=3, children=[]), 
... [T(id=40, children=[]), T(id=41, children=[]), T(id=42, children=[]),   
... T(id=43, children=[]), T(id=44, children=[]), T(id=45, children=[]),    
... [T(id=50, children=[]), T(id=51, children=[]), T(id=52, children=[]),   
... T(id=54, children=[]), [T(id=60, children=[]), T(id=61, children=[]),   
... T(id=62, children=[]), T(id=63, children=[]), [T(id=70, children=[])],  
... T(id=64, children=[])]]], T(id=8, children=[]), T(id=9, children=[])]   
>>> l1 = magic(l0)                                              
>>> l1[2].children[5].children[0].id                                        
50                                                                          
>>> len(l1[2].children[5].children[3].children)                             
5                                                                           
>>> l1[2].children[5].children[3].children[3].children                      
[T(children=[], id=70)]                                                     
>>> l1[2].children[5].children[3].children[4].id==64                        
True                                                                  

Using @rob-wouters alternative, it passes the same test too so for the test cases I tried both work ok. I will keep Rik’s because I think a standalone function can be more handy for the cases when I need this kind of behavior.

  • 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-28T05:14:37+00:00Added an answer on May 28, 2026 at 5:14 am

    I came up with this:

    def append_children(parent, iterable):
        last = None
        for i in iterable:
            if hasattr(i, '__iter__'):
                append_children(last, i)
            else:
                parent.children.append(i)
                last = i
    
    def magic(lst):
        result = []
        for i in lst:
            if hasattr(i, '__iter__'):
                append_children(result[-1], i)
            else:
                result.append(i)
        return result
    

    Example:

    >>> l_in = [T(id=1, children=[]), T(id=2, children=[]), [T(id=3, children=[]), 
    ...         T(id=4, children=[]), [T(id=5, children=[])]]]
    >>> l_expected = [T(id=1, children=[]),
    ...               T(id=2, children=[T(id=3, children=[]), 
    ...                                 T(id=4, children=[T(id=5, children=[])])])]
    >>> l_ouput = magic(l_in)
    >>> repr(l_output) == repr(l_expected)
    True
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
I am trying to loop through a bunch of documents I have to put
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

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.