Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Internal working of the list in Python
In this tutorial, we will learn about the internal working of lists in Python. We will explore how Python manages list objects in memory and examine the frame formation when we execute different list operations step by step.
List Initialization
When we create a list with elements, Python allocates memory and creates a list object ?
lis = [1, 2, 3, 4]
print(lis)
print(f"List ID: {id(lis)}")
print(f"List length: {len(lis)}")
[1, 2, 3, 4] List ID: 140712234567808 List length: 4
The list variable lis in the global frame references a list object containing four elements stored consecutively in memory.
Appending Elements
When we append an element to the list, Python adds it to the end and increases the list size ?
lis = [1, 2, 3, 4]
lis.append(8)
print(lis)
print(f"New length: {len(lis)}")
[1, 2, 3, 4, 8] New length: 5
The new element 8 is added at the end, and the list size increases from 4 to 5 elements.
Removing Elements
When we remove a specific element, Python shifts all subsequent elements to the left ?
lis = [1, 2, 3, 4, 8]
lis.remove(2)
print(lis)
print(f"New length: {len(lis)}")
[1, 3, 4, 8] New length: 4
When element 2 is removed, all subsequent elements shift one position to the left to fill the gap.
List Slicing
When we create a slice, Python creates a new list object with references to the selected elements ?
lis = [1, 3, 4, 8]
p = lis[0:3]
print(f"Original list: {lis}")
print(f"Sliced list: {p}")
print(f"Original ID: {id(lis)}")
print(f"Slice ID: {id(p)}")
Original list: [1, 3, 4, 8] Sliced list: [1, 3, 4] Original ID: 140712234567808 Slice ID: 140712234567936
Deleting by Index
Using del statement removes the element at a specific index ?
p = [1, 3, 4]
del p[0]
print(f"After deleting index 0: {p}")
print(f"New length: {len(p)}")
After deleting index 0: [3, 4] New length: 2
Memory Management Summary
| Operation | Memory Effect | Time Complexity |
|---|---|---|
append() |
Extends list at end | O(1) amortized |
remove() |
Shifts elements left | O(n) |
del list[i] |
Shifts elements left | O(n) |
| Slicing | Creates new list object | O(k) where k is slice size |
Conclusion
Python lists are dynamic arrays that automatically manage memory allocation and resizing. Understanding how lists handle operations like appending, removing, and slicing helps optimize code performance. Remember that operations requiring element shifting have O(n) complexity, while appending is typically O(1).
