Step-by-Step Explanation:
Initialization:
nums = [1, 2, 3, 4, 5]
We create a list nums with elements [1, 2, 3, 4, 5].
Appending a list:
nums.append([6, 7])
append adds the entire object as a single element at the end.
Now nums becomes: [1, 2, 3, 4, 5, [6, 7]].
Extending with a list:
nums.extend([8, 9])
extend adds each element individually to the list.
So the list now becomes: [1, 2, 3, 4, 5, [6, 7], 8, 9].
Printing length and last elements:
print(len(nums), nums[-3:])
len(nums) → 8 (total elements in the list).
nums[-3:] → last three elements: [[6, 7], 8, 9]
Final Output:
8 [[6, 7], 8, 9]Key Concept:
append vs extend:
append adds the whole object as one element.
extend adds each element individually.
Using negative indexing nums[-3:] is a quick way to access the last n elements of a list.


0 Comments:
Post a Comment