3

python array vs list

 1 year ago
source link: http://codeforces.com/blog/entry/102802
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

python array vs list

I write this blog to talk about arrays in python . As we know python lists is slow and a memory consumption because it can't assign uniform data type unlike other low languages like c and c++ ,you can read more about that in this documentation.

but there is an efficient way to make arrays like c++ ,it's the array module ,I will discuss about it and its powerful differences in terms of time and memory between it and lists.

  1. what is python array ?

python array is an array module implemented in c language unlike lists which is a cpython implementation ,it must determine a datatype like c arrays.

you can import it by the following line :

from array import array

it contains most of c datatypes like 32 bit integer :'i' ,64 bit integer :'q' , double values :'d', chars:'u'. but it doesn't contains string datatype.

  1. How to use it?

it's very similar to python lists in usage and contains most of lists functions like insert , append , count,... but the difference is that you must define array data type first . you can see this for more understanding.

But array doesn't contain sort function but you can do the following for sorting:

from array import array
#'i' means integer 32 bit datatype
a=array('i',sorted([2,3,4,1])) 
  1. examples

Here some codes to show the time and memory consumptions: — dp problem: array vs list

-graph problem 717ms using list vs 514ms using array module

Notice that not only array is faster than list but it's also less than list in terms of memory space, as you can see in the previous dp problem lists uses 77500 KB but array uses 30800 KB which is less than half of lists memory usage.

finally ,I think that array module is really useful in python competitive programming unlike lists.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK