noreasonban
noreasonban

Reputation: 3

Inserting data within a list of a list - Python

I have been trying to insert data within a list of a list, I have followed all instruction regarding inserting parameters into the list function. However, I can't get the code to work as desired.

Minimal reproducible example

table = []
row = []
table.append(row)
print (len(table))
table[0].insert(0,"a")

table.append(row)
table[1].insert(0,"b")
print(table)

Full Code Below

table = []
row = []

def main():
    print("")
    print("[E]ntry")
    print("[P]rint table")
    print("[C]ount lists")
    print("[S]elect lists")
    menuoption = input("Select option: ")
    if menuoption == "E":
        tableentry()
    elif menuoption == "P":
        print (table)
        main()
    elif menuoption == "C":
        print (len(table))
        main()
    elif menuoption == "S":
        selectlist = input("select list: ")
        print (table[1])
        main()        
    else:
        print("invalid option")
        main()   

def tableentry():     
    table.append(row)
    print (len(table))
    table[0].insert(0,"a")
    
    table.append(row)
    table[1].insert(0,"b")
    print(table)
    main()
main()

Output is this

[['b', 'a'], ['b', 'a']]

I would like the output to look like this

[['a'], ['b']]

Upvotes: 0

Views: 48

Answers (1)

Wekowoe
Wekowoe

Reputation: 46

Since row is defined at the start of your program, when you append it to your table, you probably append the reference to the object row itself (and not a new empty array every time).

Changing table.append(row) to table.append([]) should fix your problem!

Upvotes: 1

Related Questions