Create Array in Python

An array (a list) in Python is a collection of elements. Instead of just saving a value in one variable, we can use multiple lists to save multiple values at the same time.

Characteristics of Array in Java

With an array, we can store multiple values simultaneously in one variable. Let’s take a look on how we can create an array in Python. Additionally, look at some functionalities and gain a better understanding on why we use an Array.

The first index of an array in Python always starts at 0

There are a couple of things that are good to highlight – so we don’t make simple mistakes when creating an array

 

  • After the selected data type, we need to write two brackets [ ] so the compiler knows that it is an Array we want to initiate.
  • Indexing always starts at zero
  • Uninitiated integers always get the value zero and uninitiated XX always get the value null.
  • Use the correct data type for the Array, for example, you cannot save a double in a field with the data type int
  • It is not possible to change the number of elements in an array after it has been created.

Create an Array in Python

We create the Array by typing:   

 

name of Array = [ value1, value2, value3, and so on.. ]

 

  • That is, you first specify the name the array has
  • Then you simply enter the equal sign (nothing new, we have used this for variables etc.. )
  • Finally, you specify the values that the array should contain within brackets

 

Let’s take short example and show how we create the array. If we simply write:

 

field = [22, 8, 97, 3]
  • We get an array that has the name field
  • It has four elements that contains four different values
  • The index (more on that later on this page) is written below the elements/boxes
Array in Python

Index for Array in Python

The indexes (location) of each element are arranged from 0, 1, 2, 3… in ascending order.

Thus, the first value in the list has index 0. Second value index 1 and so on. There is also a corresponding negative indexing of arrays. This means that the last value also has index -1, the second last value -2 and so on. Each value has two indexes, as shown in the figure below:

Index Array Python

Therefore, we can extract the same values from a list in two ways, for example:

 

print(my_list[-1])
print(my_list[4])

Will both give the result:

 

3

The elements in the Array have a specific order

The order in which the values are assigned have a significant part for the array.

 

For example, the lists

 

my_list = [5, 2, 8, 9, 3]
my_list2 = [2, 5, 9, 8, 3]

exactly the same values. But since the values are not in the same order, the results will be different.

 

Say that we want to use the first element from each of those Arrays

 

print(my_list[0])
print(my_list2[0])

We get the results:

 

5
2

That is, as you can see, two different values