How do I define an array in python?

I want to define an array in python. how would i do it? do i need to use a list?

+2


source to share


5 answers


List is better, but you can use an array like this:

array('l')
array('c', 'hello world')
array('u', u'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])

      



More info there

+4


source


You should usually use a list. If you really want an array, you can import array :

import array
a = array.array('i', [5, 6]) # array of signed ints

      



If you want to work with multidimensional arrays you can try numpy .

+5


source


Why do you want to use an array over a list? Here's a comparison of the two that clearly states the benefits of lists.

+4


source


There are several types of arrays in Python if you want a classic array with an array unit:

import array
a = array.array('i', [1,2,3])

      

But you can also use tuples without having to import other modules:

t = (4,5,6)

      

Or lists:

l = [7,8,9]

      

A Tuple is more efficient to use but has a fixed size, while you can easily add new items to lists:

>>> l.append(10)
>>> l
[7, 8, 9, 10]
>>> t[1]
5
>>> l[1]
8

      

+3


source


If you need an array because you are working with other low-level constructs (for example, in C), you can use ctypes.

import ctypes
UINT_ARRAY_30 = ctypes.c_uint*30 # create a type of array of uint, length 30
my_array = UINT_ARRAY_30()
my_array[0] = 1
my_array[3] == 0

      

+1


source







All Articles