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']]
6
  • Please edit your question to provide a minimal reproducible example. 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. Commented May 17, 2022 at 8: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 Commented May 17, 2022 at 8: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. Commented May 17, 2022 at 8:02
  • Does this answer your question? How do I clone a list so that it doesn't change unexpectedly after assignment? Commented May 17, 2022 at 8: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. Commented May 17, 2022 at 8:07

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.