
When we append to a list, Python allocates more memory for a list than needed. Python applies some cleverness to make appending faster, as mentioned in the documentation.

That's why it is slow to insert into an array.

Internally though, Python still has to reallocate memory and move items for us, so we don't have to do it. This flexibility is good, and it looks simple from the outside. The documentation says lists are variable-length arrays.Ī variable-length array means that its length can change, either byĪdding/inserting items or removing them. Here is a link to the Python documentation that discusses list implementation briefly. So now, when we understand what an array is and how it works, we can discuss how a list in Python behaves. So if we want to add an item to the array, we need to allocate a new chunk of memory that will be big enough for all items and copy all items from the old array and write our new item there. If we want to add or remove items from an array, we must create a new array and copy values to it.īecause the extra memory we need is right after our array's Traditionally we can't change the length of the array. This memory layout makes arrays fast to read as we just read one chunk of memory sequentially, and we don't need to jump back and forth.Īrrays are also very fast when accessing items by index - as we can get the memory address of an item in the array by doing simple arithmetic. Type and stores them sequentially in physical memory, one after the other.

Traditionally (in C and similar languages), array stores values of the same So we can decide if they are the proper collection for our values.ĭifferent collections have different performance characteristics for reading and writing.Ĭhoosing a proper collection ensures we will get the performance we need for a given task. It is vital to understand how Python implements lists and how they work, Lists in Python are arrays - with all the consequences.
