Why do you use array when there is a list on Python?

Asked 2 years ago, Updated 2 years ago, 41 views

When I learned Python, I learned, "Python uses a list instead of an array."

But I saw on the Internet that when you make an array, it says that you can make an array in the array module other than the list.

I wonder what the difference is between the two.

list array python

2022-09-21 20:49

1 Answers

The list in Python has the advantage of being variable in size and being able to store any element type. Instead, it needs more memory than C's array.

Array.array is the same as C's array. Instead of storing only elements in the same type, it uses much less memory.

I compared the memory usage of the two at the bottom.

And even though you didn't ask, it's better to use NumPy than array.array (this is automatically vectorized)

when calculating with array
import array
import resource

startMem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

mylist = []
for i in range(1,100000):
    mylist.append(i)

listMem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

myarray = array.array('i')
for i in range(1,100000):
    myarray.append(i)

arrayMem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

print("To make a list:", listMem-startMem)
print("To make an array: ", arrayMem-listMem)

Run Results:

To make
list: 3768320
To make an array: 286720

(It varies slightly from time to time, but the list is always larger than the array)


2022-09-21 20:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.