DEV Community

Effy L.H.
Effy L.H.

Posted on • Edited on

Internal Implementations of List.extend() and List.append() operations in Python

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
Enter fullscreen mode Exit fullscreen mode

Sample 2

result=[]
    for i in range(n):
        result.extend([nums[0],nums[1]])
return result
Enter fullscreen mode Exit fullscreen mode

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: Alt Text
  1. List result get reference to num[0]which actually pointed to the integer instance 'int1'
  2. 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: Alt Text
  1. 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
  2. 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)