I am new to python, and coding in general. However, I ran into something that didn’t quite seem to make sense whenever going through the ‘Introduction to Python Programming’ course. Specifically in the section ‘Collections: Referencing, Methods, and extend’ when talking about issues referencing other lists, and the use of the .copy() function.
For reference without the video, the lists and problem are as follows:
list_1 = [song_1, song_2, song_3]
list_2 = list_1
list_1
return > song_1, song_2, song_3
list_2
return > song_1, song_2, song_3
#the problem is posed that with the ‘list_1 = list_2’ reference, when list_1 is altered - those changes also appear in list_2.
list_1 = [song_1, song_2, song_3]
list_2 = list_1
list_1 = list_1 + [song_4]
list_1
return > song_1, song_2, song_3, song_4
list_2
return > song_1, song_2, song_3, song_4
#instead, the instructor suggests that we reference list_1 by using the .copy() function so that the lists are not locked in reference.
list_1 = [song_1, song_2, song_3]
list_2 = list_1.copy()
list_1
return > song_1, song_2, song_3
list_2
return > song_1, song_2, song_3
#this all makes sense. However, the instructor then goes on to display the benefit of this by making changes to list_2, instead of list_1 (the reference).
list_1 = [song_1, song_2, song_3]
list_2 = list_1.copy()
list_2 = list_2 + [song_4]
list_1
return > song 1, song_2, song_3
list_2
return > song_1, song_2, song_3, song_4
#my issue with this, or what I am not understanding is. That within the context of what the instructor executed, there is no functional purpose for the list copy. In code, the same goal could have been achieved with the following
list_1 = [song_1, song_2, song_3]
list_2 = list_1 + [song_4]
list_1
return > song_1, song_2, song_3
list_2
return > song_1, song_2, song_3, song_4
#I believe what the instructor was instead trying to demonstrate is the following, where a copy of the reference list is made, then the reference list is modified without impacting list_2. As follows:
list_1 = [song_1, song_2, song_3]
list_2 = list_1.copy()
list_1 = list_1 + [song_4]
list_1
return > song_1, song_2, song_3, song_4
list_2
return > song_1, song_2, song_3
My overall questions are as follows, was there any point in doing what the instructor did in the video over the code I provided for his final return? Is my final block of code what he really intended?
Thank you!