Python Question / Quiz; What is the output of the following Python code, and why? Comment your answers below!

PythonPr's tweet image. Python Question / Quiz; What is the output of the following Python code, and why? Comment your answers below!

Answer: a) [1, 2, 3] The .copy() saves the day! › y = x.copy() creates a NEW list in memory › x.append(4) only modifies x's list › y remains unchanged: [1, 2, 3] For beginners: Lists are boxes, variables are stickers. y = x puts another sticker on the same box. y = x.copy()…


Python students seeing .copy() for the first time be like: ‘Wait… why didn’t it change too?’


W posting


A. ✅ print(x) [1, 2, 3, 4]


Option b) [1,2,3,4]


A) because the y is new list with x values if y=x then y is reference to x


Too easy Let's make it weirder: x = [[1, 2, 3]] y = x.copy() y[0].append(4) print(x) What will the output be?


A. Since y is an independent copy of subsistent changes on x so it’s [1,2,3]


Will be [1,2,3] After the copy, a new list is allocated in another memory address with the same items, but original remains at the same address.


United States Trends
Loading...

Something went wrong.


Something went wrong.