i want to define an array in python . how would i do that ? do i have to use list?
Asked
Active
Viewed 6,253 times
5 Answers
5
Normally you would 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 could try numpy.

Glorfindel
- 21,988
- 13
- 81
- 109

Mark Byers
- 811,555
- 193
- 1,581
- 1,452
4
Why do you want to use an array over a list? Here is a comparison of the two that clearly states the advantages of lists.

Community
- 1
- 1

unholysampler
- 17,141
- 7
- 47
- 64
3
There are several types of arrays in Python, if you want a classic array it would be with the array module:
import array
a = array.array('i', [1,2,3])
But you can also use tuples without needing import other modules:
t = (4,5,6)
Or lists:
l = [7,8,9]
A Tuple is more efficient in use, but it has a fixed size, while you can easily add new elements to lists:
>>> l.append(10)
>>> l
[7, 8, 9, 10]
>>> t[1]
5
>>> l[1]
8

Alfre2
- 2,039
- 3
- 19
- 22
1
If you need an array because you're working with other low-level constructs (such as you would 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

Jason R. Coombs
- 41,115
- 10
- 83
- 93