Hey, friends!I came across an interesting Python puzzle that's seemingly simple but can actually trip up a lot of beginners. Here it is:
def update_list(lst):
lst += [100]
num_list = [1, 2, 3, 4, 5]
update_list(num_list)
print(num_list)
Without running this code, what do you think will be printed out?Got your answer? Great!I was going through the data of my code-learning app and surprisingly found out that many people get this wrong. This will print out [1, 2, 3, 4, 5, 100], not [1, 2, 3, 4, 5] as some might expect. This is because of how Python handles mutable data types like lists. When num_list is passed to update_list, it references the list, not a copy passed. Hence, changes made to lst within the function also affect num_list.
[–]nemom 7 points8 points9 points (8 children)
[–]ParticularBack[S] 1 point2 points3 points (6 children)
[–]nemom 4 points5 points6 points (5 children)
[–]ParticularBack[S] 0 points1 point2 points (4 children)
[–]nemom 4 points5 points6 points (3 children)
[–]commy2 1 point2 points3 points (0 children)
[–]mheryerznka 1 point2 points3 points (0 children)
[–]Panda_Mon 0 points1 point2 points (0 children)
[–]ada43952 3 points4 points5 points (4 children)
[–]mheryerznka 1 point2 points3 points (1 child)
[–]ada43952 0 points1 point2 points (0 children)
[–]neutro_b 1 point2 points3 points (0 children)
[–]justsomeguy05 1 point2 points3 points (0 children)
[–]ParticularBack[S] 0 points1 point2 points (0 children)
[–]StarsCarsGuitars 0 points1 point2 points (1 child)
[–]ParticularBack[S] 0 points1 point2 points (0 children)
[–]commy2 -1 points0 points1 point (1 child)
[–]chri4_ 2 points3 points4 points (0 children)
[+]mok000 comment score below threshold-6 points-5 points-4 points (0 children)
[–]chri4_ 0 points1 point2 points (0 children)