Home › Interview Questions › What will be the output of the following code afte…

What will be the output of the following code after performing l1.extend(l2) and l2.append(l1)?

🟢 Easy Conceptual Fresher level
1Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

After executing l1.extend(l2), l1 becomes [1,2,3,4,5,6,7,8] because extend iterates over l2 and appends each element to l1. Then l2.append(l1) adds the entire l1 list as a single element to l2, resulting in l2 = [5,6,7,8,[1,2,3,4,5,6,7,8]]. Printing l1 will display the flattened list, while printing l2 will show the nested list at the end. The key difference is that extend unpacks the argument, whereas append treats the argument as a single object. This behavior is consistent across Python lists and is useful when you want to merge lists or add a sublist as a single element. If you need a copy of l1 inside l2, use l2.append(l1.copy()). Because l2.append(l1) stores a reference to the same list object, any later changes to l1 will be reflected inside l2's nested list. If you want to preserve the original state of l1 inside l2, you should use a shallow copy or a deep copy depending on the nested structure. This subtlety is often a source of bugs when working with mutable objects in Python.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500