How to declare an array in Python?

pynewbie picture pynewbie · Oct 3, 2009 · Viewed 2M times · Source

How do I declare an array in Python?

I can't find any reference to arrays in the documentation.

Answer

sepp2k picture sepp2k · Oct 3, 2009
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.