How to declare an array in Python? How to declare an array in Python? python python

How to declare an array in Python?


variable = []

Now variable refers to an empty list*.

Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never refer to anything other than a list", since Python is dynamically typed.


*The default built-in Python type is called a list, not an array. It is an ordered container of arbitrary length that can hold a heterogenous collection of objects (their types do not matter and can be freely mixed). This should not be confused with the array module, which offers a type closer to the C array type; the contents must be homogenous (all of the same type), but the length is still dynamic.


This is surprisingly complex topic in Python.

Practical answer

Arrays are represented by class list (see reference and do not mix them with generators).

Check out usage examples:

# empty arrayarr = [] # init with values (can contain mixed types)arr = [1, "eels"]# get item by index (can be negative to access end of array)arr = [1, 2, 3, 4, 5, 6]arr[0]  # 1arr[-1] # 6# get lengthlength = len(arr)# supports append and insertarr.append(8)arr.insert(6, 7)

Theoretical answer

Under the hood Python's list is a wrapper for a real array which contains references to items. Also, underlying array is created with some extra space.

Consequences of this are:

  • random access is really cheap (arr[6653] is same to arr[0])
  • append operation is 'for free' while some extra space
  • insert operation is expensive

Check this awesome table of operations complexity.

Also, please see this picture, where I've tried to show most important differences between array, array of references and linked list:arrays, arrays everywhere


You don't actually declare things, but this is how you create an array in Python:

from array import arrayintarray = array('i')

For more info see the array module: http://docs.python.org/library/array.html

Now possible you don't want an array, but a list, but others have answered that already. :)