Array
An array is an ordered collection of elements, and the elements can be of mixed data types. Arrays themselves are considered to be a composite data type. Python uses lists as an equivalent type. One key difference between lists and arrays is how memory is allocated. Elements of an array must be saved in adjacent or contiguous memory locations. This constraint allows for quick access of an element, but slow insertion or modification. Elements of a list, in contrast, can be saved anywhere and each element is saved with a reference to the previous element’s location. This arrangement results in fast insertion or updating of a list, but relatively poor access speed.
Syntax
Arrays are often created by using square brackets []
with a comma-separated list of individual elements inside:
array = [element0, element1, element2, element3]
Nested arrays (arrays within arrays) are also possible:
nested = [elementB, elementC]
outer = [elementA, nested, element4]
The length of the outer
array is 3 elements-long because the inner nested
array counts as an individual element. By itself, the nested
array is 2 elements-long.
Index Number
Array elements are usually referenced by an index number, which represents their position in the sequence.
The indices of most arrays start with 0:
groceryList = ["milk", "cookies", "berries", "carrots"]
// index: 0 1 2 3
- The first element
"milk"
is at index 0. - The second element
"cookies"
is at index 1. - …and so on.
Arrays in Different Languages
All contributors
- Christine_Yang271 total contributions
- Anonymous contributorAnonymous contributor1 total contribution
- garanews222 total contributions
- Not-Ethan48 total contributions
- Anonymous contributorAnonymous contributor3071 total contributions
- christian.dinh2476 total contributions
- Christine_Yang
- Anonymous contributor
- garanews
- Not-Ethan
- Anonymous contributor
- christian.dinh
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.