0

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']]
  • Please [edit] your question to provide a [mre]. In specific, we don't know what `input` you are providing to this function. Ideally, the code would omit the manual input and instead use a hardcoded sequence of commands. – MisterMiyagi May 17 '22 at 08:00
  • What the logic behind ? Why do you need to select `a` for the first list and `b` for the second one ? We can't help without more informations – Marius ROBERT May 17 '22 at 08:00
  • Note that there is only *a single* `row` object that is appended to `table` *twice*. Consequently, both `table[0].insert` and `table[1].insert` will insert to the *same* list, and printing `table` will show the same sublist twice. – MisterMiyagi May 17 '22 at 08:02
  • Does this answer your question? [How do I clone a list so that it doesn't change unexpectedly after assignment?](https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment) – MisterMiyagi May 17 '22 at 08:04
  • So should I provide some kind of counter to the "row" object, I have tried " if row == 0: row = row elif row = row +1. but I did not get any good results. – noreasonban May 17 '22 at 08:07
  • I will write up some short code, for that minimal reproducible example, give me a few moments. – noreasonban May 17 '22 at 08:08

1 Answers1

1

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!

Wekowoe
  • 46
  • 1
  • 3