Lists and arrays in Python are quite similar but they’re certainly not the same. Let’s create a list and an array in python and see the differences.
Creating a list in python:
# create a list of numbers in python
myNumbersList = [1, 2, 3, 4, 5]
print (myNumbersList)
print (myNumbersList[3])
print (myNumbersList[3]+myNumbersList[4])
[1, 2, 3, 4, 5]
4
9
As can be seen, lists behave somewhat like arrays, indeed we can even do maths on the elements of the list.
Trying the following code, we can see how we can access ‘slices’ from the list. The 1: denotes miss the first value of the list, and the second digit (if any) denotes ‘up to but not including’ an element number
# create a list of numbers in python
myNumbersList = [1, 2, 3, 4, 5, 6, 7, 8]
print (myNumbersList[1:4])
print (myNumbersList[1:])
[2, 3, 4]
[2, 3, 4, 5, 6, 7, 8]
So lists appear to be working rather like arrays, but in the following we see key differences
If we create an array, we need to use numpy to do this:
import numpy
myNumbersArray = array([3, 6, 9, 12])
y = myNumbersArray/3.0
print(y)
[1. 2. 3. 4.]
We see that we can divide all elements in an array by 3 for example. But let’s try that on a list
# create a list of numbers in python
myNumbersList = [3, 6, 9, 12]
y = myNumbersList/3.0
print (y)
TypeError Traceback (most recent call last) <ipython-input-44-debe4f8a7c32> in <module> 1 # create a list of numbers in python 2 myNumbersList = [3, 6, 9, 12] ----> 3 y = myNumbersList/3.0 4 print (y) TypeError: unsupported operand type(s) for /: 'list' and 'float'
We can see a big error is thrown.
Checking to see what type a variable is we can simply use ‘type’
import numpy
myNumbersArray = array([3, 6, 9, 12])
type(myNumbersArray)
numpy.ndarray
myNumbersList = [3, 6, 9, 12]
type(myNumbersList)
list