List vs Numpy Array and Tuple | applied electronics engineering

# List vs Numpy Array and Tuple

By Applied Electronics - Wednesday, March 15, 2017 No Comments
In python programming language, List and Tuple are predefined object types. They are used to represent collections of data type variables. The Numpy Array is also similar. Both List and Numpy Array can be used for writing bunch of numbers and perform calculation. But what is the difference and which one is preferred?

First let's look at List and Tuple because they are also closely related. So what is the difference between List and Tuple in Python programming language?

A List in Python is collection of objects written inside a square bracket. The objects within the square bracket can be any data type object in python such as integers, characters, strings or even another list. An example of list is as follows,

L = [10, 'z', max, 3 + 4j, 'Hello world!']

Note that in python, a List like L is itself an object.

A Tuple is also an object like List but is immutable. Immutable means that it's elements cannot be reassigned or reordered. A Tuple is declared using parenthesis. For example,

t=(2,3)

is a tuple.

Now lets see some of the similarities and differences between List and Numpy Array. A list is a sequence of objects, endowed with methods that can perform certain operations on its contents like searching and counting. You can do numerical calculations with lists but generally it is not the best or convenient way. One reason is that List contains objects of different data types. But for numerical computation you want objects of the same data type. Numpy module which you need to import has a class called array. This array is better suited for handling computation of set of variables because they are all of the same data type.

In python before you can use array data types you need to import numpy in the following way.

import numpy as np

Then you can use the np namespace for doing numerical calculation and declaration. For example you wanted to create a one-dimensional array of zeros. You can do that as follows,

>>> import numpy as np
>>> a = np.zeros(4)
>>> a
array([ 0.,  0.,  0.,  0.])

Similarly for 1D ones vector type,

>>> b = np.ones(6)
>>> b
array([ 1.,  1.,  1.,  1.,  1.,  1.])

You are not limited to ones and zeros 1D vector. To create two dimensional zeros or ones type the following.

>>> A = np.zeros((2,4))
>>> A
array([[ 0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.]])

Now consider examples of List and Numpy Arrays. The following creates a List L,

>>> L = [3.14, 20.3, 100]
>>> L
[3.14, 20.3, 100]

Now the same using Numpy array is as follows,

>>> a = np.array([3.14, 20.3, 100])
>>> a
array([   3.14,   20.3 ,  100.  ])