Python Basics: Understanding Lists and Append

20 students. One simple Python problem. Most got it wrong. Which code gives the same output for both a and b? Code 1: a = [1, 2, 3] b = a b.append(4) print(a) Code 2: a = [1, 2, 3] b = a.copy() b.append(4) print(a) Take a guess before you run it. In interviews, questions are rarely difficult. They are designed to check one thing: Do you really understand the basics? Most people rush to answer. Very few stop and think. What’s your answer? #Python #CodingInterview #DataAnalytics #LearnPython #CareerGrowth

Drop your answer: 1 or 2?

Like
Reply

Code 1 will give same outputs for print(a) and print(b) as using b=a doesn't create a new variable b, but simply references a. Using a.copy() in the 2nd code will create a new variable b and a remains separate.

Like
Reply

We never get output for b, as we never print it, we get the output for a in both the code

Like
Reply

Code 1 It’s not a copy, it’s just an alias. They’re basically the same person with two different names.

Like
Reply

b and a both change output

Like
Reply

Means different output

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories