Reputation: 5
I have this part of code isolated for testing purposes and this question
noTasks = int(input())
noOutput = int(input())
outputClist = []
outputCList = []
for i in range(0, noTasks):
for w in range(0, noOutput):
outputChecked = str(input())
outputClist.append(outputChecked)
outputCList.append(outputClist)
outputClist[:] = []
print(outputCList)
I have this code here, and i get this output
[[], []]
I can't figure out how to get the following output, and i must clear that sublist or i get something completely wrong...
[["test lol", "here can be more stuff"], ["test 2 lol", "here can be more stuff"]]
Upvotes: 0
Views: 171
Reputation: 42758
In Python everything is a object. A list is a object with elements. You only create one object outputclist
filling and clearing its contents. In the end, you have one list multiple times in outputCList
, and as your last thing is clearing the list, this list is empty.
Instead, you have to create a new list for every task:
noTasks = int(input())
noOutput = int(input())
output = []
for i in range(noTasks):
checks = []
for w in range(noOutput):
checks.append(input())
output.append(checks)
print(output)
Upvotes: 1
Reputation: 6693
Instead of passing the contained elements in outputClist
to outputCList
(not the greatest naming practice either to just have one capitalization partway through be the only difference in variable names), you are passing a reference to the list itself. To get around this important and useful feature of Python that you don't want to make use of, you can pretty easily just pass a new list containing the elements of outputClist
by changing this line
outputCList.append(outputClist)
to
outputCList.append(list(outputClist))
or equivalently, as @jonrsharpe states in his comment
outputCList.append(outputClist[:])
Upvotes: 1