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

Question:

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()
Asked By: user2334659

||

Answers:

If I understand, you wan’t to replace the element at the value i by temp_list?
If it’s that here is some code (not tested):
code 1:

for i, _ in enumerate(address_list): 
    """enumerate take your list and transform it into a list contening a tuple contening the index and the value -> enumerate(["a", "b", "c"]) == [(0, "a"), (1, "b"), (2, "c")]"""
    temp_list = [] # I think you don't need to have the old value
    with open(file_path_simple, 'r') as fp:
        for ln in fp:
            ln = ln.strip('n')
            temp_list.append(ln)
        # don't need to close because at the end of the "with" statement
        #the file is automaticly close
address_list[i] = [] # replace the old value by a list so you can 
                     #append
for j in temp_list:
    address_list[i].append(j)

(not tested) code 2:

for i, _ in enumerate(address_list):
    temp_list = []
    with open(file_path_simple, 'r') as fp:
        for ln in fp:
            ln = ln.strip('n')
            temp_list.append(ln)
    address_list[i] = temp_list

don’t mind my poor english,
Flayme

Answered By: Flayme

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()
Answered By: OneCricketeer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.