2

i want to define an array in python . how would i do that ? do i have to use list?

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
Hick
  • 33,822
  • 46
  • 145
  • 240

5 Answers5

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.

Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
4

List is better, but you can use 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 infos there

Kami
  • 5,791
  • 8
  • 37
  • 50
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
  • 16,667
  • 6
  • 46
  • 63
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
  • 1,899
  • 3
  • 17
  • 21
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
  • 39,015
  • 10
  • 79
  • 86