What would you expect to be the output of the following code snippet: `a = [1, 2, 3]; b = a; b[1] = 4; print(a); print(b);`, and why?

a = [1, 2, 3] b = a b[1] = 4 print(a) print(b) The output of this would be:[1, 4, 3] [1, 4, 3] This occurs because lists in Python are pass-by-reference, rather than pass-by-value. What this means is that when we assign b to a, we are not copying the list [1,2,3] to b, we are just copying the reference! So when we change the second element of b to 4, then print a and b, both of them print [1,4,3], because both of them point to the same list.

Answered by Ibrahim Q. Python tutor

2190 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Generate an array of integers from 0 to 99 and split it into two smaller arrays. Each smaller array will contain half of the original.


What is the outcome of the following code? print(2*[3,4,5])


how to compute the factorial of a number.


Write a function that takes a string, and outputs that string formatted in camelcase. (alternating upper and lower case for each character, e.g. cAmElCaSe)


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo
Cookie Preferences