+ 1

This Program Does Something Weird. Can You Explain Why?

Here’s a small Python/JS snippet: a = [1, 2, 3] b = a a.append(4) print(b) Output: [1, 2, 3, 4] Why did b change too? 🤔 Beginners are always surprised by this. Let’s discuss!

7th Aug 2025, 7:14 PM
SAIFULLAHI KHAMISU
SAIFULLAHI KHAMISU - avatar
2 Respostas
+ 4
Q&A is for asking genuine programming-related questions and getting help with code. Use the challenge thread for challenges. Mind the initial post. Use the news feed for sharing your thoughts and for opinion-based discussions. https://www.sololearn.com/discuss/1270852/?ref=app
7th Aug 2025, 7:32 PM
Lisa
Lisa - avatar
+ 2
In this case a is a pointer, and b = a assigns a pointer stored in a to b. Well in reality its slightly more complicated than this, but same principle. To properly assign arrays, you need to actually copy the memory. Here is more on this topic, with examples: https://www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK/array-copying-in-python/
7th Aug 2025, 7:20 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar