Memory Allocation to List in Python

In this class, we discuss how memory allocation to list in python is done.

For Complete YouTube Video: Click Here

Memory Allocation to list

First, the reader should have a basic understanding of the list data type. Click here.

In our beginning classes, we discussed variables and memory allocation. These classes will help you a lot in understanding the topic. Click here.

Let’s take an example and understand how memory is allocated to a list.

Memory Allocation to List in Python
Memory Allocation

The above diagram shows the memory organization.

Each memory location is one byte. The address of the memory location is given.

For the understanding purpose, we are taking a simple memory organization.

There are different organizations that take two bytes in a memory location.

These concepts are discussed in our computer organization course.

Example:

a=[1,5,6,6]

The element 1 is of type integer.

Assume integer type is taking 2 bytes of memory space.

The decimal value one is converted to binary value 1, taking 16 bits.

The memory diagram is shown below.

Memory Allocation to List in Python1
Integer in Memory

Assume, To store the first element in the list. The compiler assigned the memory location 50 and 51 because integers needed 2 bytes.

The first element is referencing the memory location 50.

In the list, 50 are saved.

Similarly, assume the second element is assigned memory locations 60 and 61.

The starting location 60 is saved in the list.

The memory locations 70 and 71 are assigned for element 6.

The starting address 70 saved in third and fourth element position in the list.

Because of the concept of interning, both elements refer to exact memory location.

The list is shown below.

a=[50,60,70,70] This is how memory locations are saved in the list.

Example Memory Allocation to List within List

a=[1,5,6,6,[2,6,5]]

How memory is allocated is given below.

a=[50,60,70,70,[80,70,60]]

The list within the list is also using the concept of interning. Identical elements are given one memory location.

Practical examples to check the concept are given below.

a=[1,5,6,6]

print(id(a[0]))

print(id(a[1]))

print(id(a[2]))

print(id(a[3]))

Output:

8291264, 8291328, 8291344. 8291344

Example 2:

a=[1,5,6,6,[2,6,5]]

print(id(a[0]))

print(id(a[1]))

print(id(a[2]))

print(id(a[3]))

print(id(a[4][0]))

print(id(a[4][1]))

print(id(a[4][2]))

Output: 8291264, 8291328. 8291344, 8291344, 8291280, 8291344, 8291328.