-1

I am writing a program that is supposed to take 10 test scores from students and their names and put that information into a list inside of a list. I saw a problem with the fact that I was repetitively .append -ing things to my 'info' list and was getting duplicate data. However, when I try to fix it the program keeps returning either empty lists or lists with only the second set of name and test scores. I do not know why this is happening, any help at all would be greatly appreciated.

I have tried:

  • del info[:]
  • info.clear()
  • for i in range len(info): info.pop()

w

testinfo = []
score = 0
testnum = 0
name = ''
info = []
info2 = []
name = input('Enter a student name')
while name != '0':
    info.append(name)
    for i in range(0, 10):
        testnum = testnum+1
        print('Enter a score for test', testnum)
        score = int(input())
        info.append(score)
    testnum = testnum-10
    testinfo.append(info)
    name = input('Enter a student name')
    del info[:]
print(testinfo)

Expected result:[[student1name,1testscore1,1testscore2,etc.],[student2name,2testscore1,2testscore2,etc.]]

Actual result: [[], []] or [[student2name,2testscore1,2testscore2,etc.], [student2name,2testscore1,2testscore2,etc.]]

W Murphy
  • 9
  • 1

2 Answers2

0

Try insted of directly appending info to testinfo use:

testinfo.append(copy.deepcopy(info))

I think that your problem is that your info list is pointing to list inside of listinfo. So if your delete info list your are also deleting the content of infolist. https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/. I think you need to import copy. Hope this helps.

0
info = []
  • creates a new list somewhere in memory
  • creates a binding called info which points to that memory area
testinfo.append(info)
  • creates a copy of the binding info
  • stores that binding inside the testinfo list
del info[:]
  • deletes the memory area accociated with info
  • the binding in testinfo points to the same memory location and is deleted as a result

Instead of deleting the list manually you could simply reassign a new list object:

info = []

Or put the info into the scope of the loop.

asynts
  • 2,213
  • 2
  • 21
  • 35