+ 5

Not all popular lists functions

I think it is necessary to add to course an article describing what happens if we write list2=list1. There is a lot of users questions why list2 changes if we change list1. Such questions are in challenges too.

17th Jan 2018, 11:35 AM
Petr Leliaev
Petr Leliaev - avatar
4 Answers
+ 2
Its because for list, just pure = creates an exact copy. An exact copy will copy whatever the first term is only if methods are used, not operations. If you don't want it, create a dry copy with [:]
17th Jan 2018, 1:49 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
the cause is...... list2 assigned list1's value😊. it changes by list1.
17th Jan 2018, 5:57 PM
Md Habibullah
Md Habibullah - avatar
+ 1
@Pegasus thank you! I'd like to see such an explanation in the course, I think it's important for all learners
17th Jan 2018, 4:41 PM
Petr Leliaev
Petr Leliaev - avatar
0
# you can use id() and 'is' to examine the relationships my_list = [1, 2, 3] # this is assignment, an additional reference to the same object my_list_reference = my_list print('These are identical references', my_list is my_list_reference) print('they point to same object in memory ?', id(my_list_reference) == id(my_list)) # you can make independent objects(copies) via the constructor my_list_copy = list(my_list) print('these are identical refernces?', my_list_copy is my_list) print('they point to same object in memory?', id(my_list_copy) == id(my_list))
17th Jan 2018, 6:09 PM
richard