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
- Anonymous contributor
- christian.dinh
- Christine_Yang
- Anonymous contributor
- garanews
- Not-Ethan
Contribute to Docs
- 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.
Learn more on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours