user10614001
user10614001

Reputation:

what does python "array" module do and why should i use it instead of a list?

I have recently stumbled across the "array" module in python. i saw it used something like this:

import array
a = array.array('i')

what does line 2 do? why should i use "array" instead of a simple list?

Upvotes: 2

Views: 1757

Answers (2)

Shiva Gupta
Shiva Gupta

Reputation: 27

The line 2 of your code means: The first 'array' represents the module name. The second 'array' represents the class name array for which we are creating an array object. The 'i' here represents the typedata since in arrays are a collection of same data type. The 'i' represents the integer elements will be stored in the array a.

We should use array when we want to store same type of data because its execution is much faster than the lists. Also, arrays take up less space than lists.

Upvotes: 0

Adithya Ramanathan
Adithya Ramanathan

Reputation: 146

The difference between an array and a list is that the type of object stored in the array container is constrained. In line 2:

a = array.array('i')

You are initializing an array of signed ints.

A list allows you to have a combination of varying datatypes (both custom and basic) if desired. For example:

l = [13, 'hello']

You would choose to use an array over a list for efficiency purposes if you can assure the datatype found in the array to all be the same and of a certain, basic type.

More information can be found here: Description of Array Module Usage

Upvotes: 5

Related Questions