How to declare an array in Python?
variable = 
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.
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 # 1arr[-1] # 6# get lengthlength = len(arr)# supports append and insertarr.append(8)arr.insert(6, 7)
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 (
arris same to
appendoperation is 'for free' while some extra space
insertoperation is expensive
Check this awesome table of operations complexity.
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. :)