0
test = list()
test2 = list()
numbers = ["1", "2", "3", "4", "5"]
    
    
for number in numbers:
   test.append(number) 
   if len(test) >= 3:
        test2.append(test)
    
   test.clear()

So I want to clear test after I appended it to test2 but when I do so the list inside test2 gets also cleared how can I avoid that?

so they look like that after clear:

test = []
test2 = []

but I want test2 to be [["1", "2", "3"]]

Jacob Lee
  • 4,405
  • 2
  • 16
  • 37
  • You can use the list.copy function so you append a copy of test to test2. https://www.programiz.com/python-programming/methods/list/copy – Artory May 05 '21 at 15:27
  • You will have to append a copy instead of a reference to the same list. – kaya3 May 05 '21 at 15:27

1 Answers1

2

You need to copy the version of the list that you don't want to delete.

test = list()
test2 = list()
numbers = ["1", "2", "3", "4", "5"]


for number in numbers:
   test.append(number) 
   if len(test) >= 3:
     test2.append(test[:]) # This grabs a slice of the entire list, effectively copying it

test.clear()
C_Z_
  • 7,427
  • 5
  • 44
  • 81
  • For basic questions like this, you should look to see if there's a duplicate first before answering - please see the section on answering "well-asked questions" here https://stackoverflow.com/help/how-to-answer – kaya3 May 05 '21 at 15:31