Let’s take a deep dive into the internal implementation of List.extend() & List.append() operations:
Suppose the list nums[] contains 7 integer elements, and we're about to execute lines as below:
Sample 1
result=[]
for i in range(n):
result.append(nums[0])
result.append(nums[1])
return result
Sample 2
result=[]
for i in range(n):
result.extend([nums[0],nums[1]])
return result
Analysis of Internal Implementation
Sample 1
- When we execute result.append(nums[0]),result.append(nums[1]), the internal implementation will be like as below:
- List result get reference to num[0]which actually pointed to the integer instance 'int1'
- Then list result get reference to num[1]which actually pointed to the integer instance 'int2'
Sample 2
- When we execute result.extend([nums[0],nums[1]]), the internal implementation will be like as below:
- Contents inside the parentheses of .extend() function can be treated as a temp list which actually pointed to the same integer objects as list nums
- Then, the list result receive those references to those integers through that temp list
This post is also a complement to my previous post:
https://dev.to/effylh/leetcode-1470-shuffle-the-array-3ok5
Top comments (0)