2

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

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.