How to declare an array in Python?
How do I declare an array in Python?
I can't find any reference to arrays in the documentation.
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.
Read more... Read less...
This is surprisingly complex topic in Python.
Check out usage examples:
# empty array arr =  # 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 # 1 arr[-1] # 6 # get length length = len(arr) # supports append and insert arr.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 array intarray = 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. :)
This is how:
my_array = [1, 'rebecca', 'allard', 15]
For calculations, use numpy arrays like this:
import numpy as np a = np.ones((3,2)) # a 2D array with 3 rows, 2 columns, filled with ones b = np.array([1,2,3]) # a 1D array initialised using a list [1,2,3] c = np.linspace(2,3,100) # an array with 100 points beteen (and including) 2 and 3 print(a*1.5) # all elements of a times 1.5 print(a.T+b) # b added to the transpose of a
these numpy arrays can be saved and loaded from disk (even compressed) and complex calculations with large amounts of elements are C-like fast.
Much used in scientific environments. See here for more.