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

1414 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What can be used to iterate through a list in python?


Which four data types are used in Python? Can you give an example of each?


How could I write a program to convert Km/h to m/s in python


Whats the output of "for i in "hello world": print(i)" and why/how is this achieved


We're here to help

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

© MyTutorWeb Ltd 2013–2024

Terms & Conditions|Privacy Policy