Search code examples
pythonlistnested

How to create a nested list in python by appending to an existing list


I have a list called address_list and I want to iterate through it. Each value in the address_list I iterate through is run through another function which will return a new list called temp_list. I then want to nest the values of temp_list under the original value in address_list before moving on and doing the same thing to the next value in address_list.

Essentially it should look like this (with the address_list index on the left and the temp_list on the right):

[0] - [1,2,3]

[1] - [1,5,6,7,8,35]

[2] - [3,543,34,84,3,8,53]

This is the code I am trying to use:

for i in range(0,len(address_list)):
   
    #some code skipped where file_path_simple gets new values each time
    with open(file_path_simple, 'r') as fp:
        for ln in fp:
            ln = ln.strip('\n')
            temp_list.append(ln)
        fp.close()

    for j in temp_list:
        address_list[i].append(j)

This is giving me the following error:

Traceback (most recent call last): File "z:[path_redacted]\tracer.py", line 155, in <module> 
    address_list[i].append([]) 
AttributeError: 'str' object has no attribute 'append' 

The full code is LONG but hopefully this chunk will give a better idea:

address_list = []
temp_list = []
G = nx.Graph()
address_list.append(address)

#adds the root
G.add_node(address_list[0])

for i in range(0,len(address_list)):
    #print for testing purposes
    print(address_list[i])
    
    if i == target:
        tracePath(address, address_list[i])
    
    #query the address
    txQuery(address_list[i])
    parser()

    #write output to temp_list which will be the nested list
    file_path_simple = r'Z:\[path_redacted]\tx_list_simple.txt'
    with open(file_path_simple, 'r') as fp:
        for ln in fp:
            ln = ln.strip('\n')
            temp_list.append(ln)
        fp.close()

    #create the nested list for associated addresses
    address_list[i].append([])
    for j in temp_list:
        address_list[i].append(j)

    #create the children of the parent node which was queried
    for i in address_list[0][i]:
        G.add_node(i)
        G.add_edge(*[address_list[0],i])
        address_list.append(i)
    
    temp_list.clear()

Solution

  • From what I can tell, you want to read a file into a list, then put that list into another one? You don't need to do that in a loop

    But you can still loop over the address_list after it is populated from that file

    G = nx.Graph()
    G.add_node(address)
    
    address_list = []
    
    file_path_simple = r'Z:\[path_redacted]\tx_list_simple.txt'
    with open(file_path_simple, 'r') as fp:
        temp_list = [ln.strip('\n') for ln in fp]
        address_list.append(temp_list)
    
    for i, a in enumerate(address_list):
        if i == target:
            tracePath(address, a)
        
        # query the address
        txQuery(a)
        parser()