+ 6
doubling in quiz - values vs references
Attempting to understand one tricky quiz from challenges library. a = [[0]*2]*2 a[0][0]=5 print(a) The output is [[5,0][5,0]] Right? For me it looked like mistake (as usually indeed). When run test in playground I realized how it works and it was a kind of little discovery. first doubling [0]*2 - extends list by doubling items of the list. # second doubling [[0]*2]*2 - creates list of lists. The difference between first and second doubling is doubling values vs doubling references. Looks simple for somebody but for me it is quite tricky likn of code! Isn't it?
4 Answers
+ 2
More over I found and rechecked another tricky quiz. It took time to understand hwo it works.
With some modifications the quiz looks like following:
def build_list(element, to=[]):
to.append(element)
#print(to)
#print(id(to))
return to
list1=build_list(1)
print(list1)
list2=build_list(2)
# Going to see list2=[2] but actually list2=[1,2] because we invoke function "build_list" without passing any reference
# to any list. So list "to" is used by default. And by default it references to the same memory block every time
# when "build_list" is invoked without second parameter.
print(list2)
# But if pass both parameters explicitly the returned result will be more predictible.
list3=[]
list3=build_list(3,list3)
print(list3)
list3=build_list(4,list3)
print(list3)
+ 1
Wow! You cleared it up for me!!
+ 1
Great! It actually means I cleared it up at least for two persons - you and me :)
+ 1
Congrats and thank you!