To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Arrays and lists in Python

In computer languages, an array is a structure used to store multiple related items in an indexed format that somewhat resembles the actual memory it is representing.

One of the most important things to notice about arrays is that they begin at index 0. That means the first element of the array is the 0th element.

Whilst Python does have an actual array data type, the most common array used is the list (much like ZPE). 

Arrays

An array with some integer values within it.

Notice the first index, that is, where n = 0, is the 0th element.

Lists in Python

Python arrays can be defined very quickly using the [] notation. In most languages, a list differs from an array in that each element of the list can be of a different type.

The following sample demonstrates declaring a list of 10 numbers of the Fibonacci Sequence.

Python
fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print (fib)
    

Arrays can be given empty values and a default length by simply defining them as having a certain number of empty elements as shown below:

Python
arr = [""] * 5
print (arr)
    

The previous sample will create precisely 5 empty strings within an array. This array will have a fixed length, so it is not possible to access an element larger than the array.

If numbers are required, it may be a good idea to create a list with 0s as the initial value:

Python
arr = [0] * 5
print (arr)
    

Appending an element

Appending an element allows an array to expand in size and add an element to it. To append to an array, the list.append method is used:

Python
fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
fib.append(144)
print (fib)
    

Accessing an element

An element within the list can be accessed instantly using its index. In Python, the square bracket ([]) syntax is used:

Python
fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# Since Python indexes start on 0, this will return the value 3.
print (fib[2])
    

Elements at a certain index can also be set using the same notation:

Python
fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# The number 3 will become 10
fib[2] = 10
print (fib)
    

List length

All programming languages provide some method of determining the length of an array or list. Python is no exception. Within Python an internal method known as len will obtain the length of certain values such as the list:

Python
fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print (len(fib))
    
The len method will return a human-readable length, so a list with just one element will return 1 and one with no elements will return 0.
Provide feedback on this page
Comments are sent via email to me.