append to list and clear /u/janflip Python Education

I was wondering what I did wrong in my python 3.12 program. I found out that clearing a list after appending it clears the append list part. Here is my test program

# python script to test append list and clear list # list1 = [1,2,3,4,5,6] list2 = [7,8,9] list1.append(list2) # list1 = list1 + list2 print(list1) list2.clear() print(list1) 

The output is as follows:

[1, 2, 3, 4, 5, 6, [7, 8, 9]]

[1, 2, 3, 4, 5, 6, []]

The list1.append(list2) command doesn’t copy list2 into list1 but makes a reference to list2. Why is this done? Is this for efficiency reasons??

submitted by /u/janflip
[link] [comments]

​r/learnpython I was wondering what I did wrong in my python 3.12 program. I found out that clearing a list after appending it clears the append list part. Here is my test program # python script to test append list and clear list # list1 = [1,2,3,4,5,6] list2 = [7,8,9] list1.append(list2) # list1 = list1 + list2 print(list1) list2.clear() print(list1) The output is as follows: [1, 2, 3, 4, 5, 6, [7, 8, 9]] [1, 2, 3, 4, 5, 6, []] The list1.append(list2) command doesn’t copy list2 into list1 but makes a reference to list2. Why is this done? Is this for efficiency reasons?? submitted by /u/janflip [link] [comments] 

I was wondering what I did wrong in my python 3.12 program. I found out that clearing a list after appending it clears the append list part. Here is my test program

# python script to test append list and clear list # list1 = [1,2,3,4,5,6] list2 = [7,8,9] list1.append(list2) # list1 = list1 + list2 print(list1) list2.clear() print(list1) 

The output is as follows:

[1, 2, 3, 4, 5, 6, [7, 8, 9]]

[1, 2, 3, 4, 5, 6, []]

The list1.append(list2) command doesn’t copy list2 into list1 but makes a reference to list2. Why is this done? Is this for efficiency reasons??

submitted by /u/janflip
[link] [comments] 

Leave a Reply

Your email address will not be published. Required fields are marked *