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.

IQ
Answered by Ibrahim Q. Python tutor

2471 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Write a program that can convert between celcius and farenheit temperature scales


Write a recursive function that takes any integer n and prints the nth Fibonacci number.


Given a list of N numbers, use a single list comprehension to produce a new list that only contains those values that are: (a) even numbers, and (b) from elements in the original list that had even indices .


When to use a dectionary or a list


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–2025

Terms & Conditions|Privacy Policy
Cookie Preferences