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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T22:57:32+00:00 2026-05-26T22:57:32+00:00

The following code recursively processes a list of dictionaries into a tree while building

  • 0

The following code recursively processes a list of dictionaries into a tree while building an HTML output string. I’m getting a scope access error when trying to access the output string variable from within the recursing function. However, it has no problem accessing the nodes list object in the same scope- and in fact the function worked fine before I added the output var. What’s the deal here?

Sample:
http://ideone.com/Kg8ti

nodes = [ 
{ 'id':1, 'parent_id':None, 'name':'a' },
{ 'id':2, 'parent_id':None, 'name':'b' },
{ 'id':3, 'parent_id':2, 'name':'c' },
{ 'id':4, 'parent_id':2, 'name':'d' },
{ 'id':5, 'parent_id':4, 'name':'e' },
{ 'id':6, 'parent_id':None, 'name':'f' }
]

output = ''

def build_node(node):
    output += '<li><a>'+node['name']+'</a>'
    subnodes = [subnode for subnode in nodes if subnode['parent_id'] == node['id']]
    if len(subnodes) > 0 : 
        output += '<ul>'
        [build_node(subnode) for subnode in subnodes]
        output += '</ul>'
    output += '</li>'
    return node

output += '<ul>'
node_tree = [build_node(node) for node in nodes if node['parent_id'] == None]
output += '</ul>'   

import pprint
pprint.pprint(node_tree)

Error:

Traceback (most recent call last):
  File "prog.py", line 23, in <module>
    node_tree = [build_node(node) for node in nodes if node['parent_id'] == None]
  File "prog.py", line 13, in build_node
    output += '<li><a>'+node['name']+'</a>'
UnboundLocalError: local variable 'output' referenced before assignment
  • 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-26T22:57:33+00:00Added an answer on May 26, 2026 at 10:57 pm

    The error stems from this:

    output = ''
    def add(s):
        output = output + s
    

    which is equivalent to output+=s. The two output-s in the expanded form refer to different scopes. The assignment sets a local variable while the expression on the right references a global (because local isn’t set yet).

    Python detects such conflicts and throws an error.

    Others have suggested using global to let Python know both output-s refer to the global scope but since you’re concatenating strings here, there’s an even better idiom used for this task in Python:

    output_list = []
    def add(s):
        output_list.append(s)
    # ...
    output = ''.join(output_list)
    

    Here you’re not setting a variable in the function so there’s no need for global. Strings from all calls are added to a list and finally joined using '' (empty string) as separator. This is much faster than adding strings using += because strings in Python are immutable so every time you add two strings, Python has to create a new string. This introduces a lot of memory copying.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code that does something very simple: visits recursively a tree
I have the following code which recursively operates on each element within a List
I have a problem with the following code: public static void RestoreToolStripMenuItem(ToolStripMenuItem item, List<string>.Enumerator
I'm writing code to recursively replace predefined variables from inside a given string. The
I have the following code: public void DriveRecursion(string retPath) { string pattern = @[~#&!%\+\{\}]+;
I have the following code snippet. I'm trying to list all the files in
I'm testing the following code to populate a dictionary recursively. However the type inference
I have following code to divide one number recursively by another number: #include <iostream>
consider the following code if insert() return the list itself. def sieve(l): if not
I am loading photos in a custom leaderboard recursively by using following code in

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.