how a = b works in case of list and strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how a = b works in case of list and strings

https://code.sololearn.com/c6AheOkg0oEN/?ref=app in this code even after appending list it gives True while this isn't the case with strings

16th May 2020, 8:34 AM
Bhavuk Sharma
Bhavuk Sharma - avatar
2 Answers
+ 6
late_1 and late_2 point to the same list, there is actually only one list that you are modifying, and that change will reflect in both variables. If you want to make a separate copy, you can do late_2 = late_1.copy() or late_2 = late_1[:] This is a shallow copy, so it works only if there are no nested collections inside the list. In the other case, a string is always immutable. When you do this: s = s + 's' You are actually creating a new string in memory, that has an extra letter. And you reassign it to the s variable, while x still points to the old string.
16th May 2020, 8:45 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Python variable names point at objects. late_1==late_2 causes late_1 to point at the same object as late_2. modifies the late_2 object in-place, so late_1 is affected as well. You can see this effect by printing both the lists👇 https://code.sololearn.com/c1Y65qNV76AI/?ref=app
16th May 2020, 8:46 AM
Arsenic
Arsenic - avatar