Learning Python: Programming and Data Structures- Tutorial 11- Arrays, Sorting and Searching

For all practical purposes, you can use Lists as Arrays in Python. This quick tutorial will walk you through how you can use Lists as Arrays, how you can sort and search, and how you can create 2D arrays using lists of lists.


Let's walk through this simple example of a 1 Dimensional List

# Let's load the Python Interactive Interpreter

Python 2.7.3 (default, Aug  1 2012, 05:16:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

# Let's create an array using a list data structure
>>> array = []
>>> array.append(1)
>>> array.append(2)
>>> array.append(4)
>>> array.append(8)

# Let's display this array
>>> print array
[1, 2, 4, 8]

# Printing elements at a specified index in the array
>>> print array[3]
8

# Let's modify what we stored at Index 3
>>> array[3] = 10
>>> print array
[1, 2, 4, 10]

# Let's create a second array
>>> secondArray = [1,2,3]
>>> print array + secondArray

# An array formed by concatenating the two arrays
[1, 2, 4, 10, 1, 2, 3]

# Now, let's create a third array

>>> thirdArray = [10,98,1,2,4,2,0]

# This is how we sort an array

>>> thirdArray.sort()
>>> print thirdArray
[0, 1, 2, 2, 4, 10, 98]

# This is how we find the index of a particular element in the array

>>> print thirdArray.index(1)
1
>>> print thirdArray.index(999)

# If we look for an element which is not present in the list, we get an error of this kind

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 999 is not in list

# So here is what we can do instead

>>> if 999 in thirdArray: print thirdArray.index(999)
... 

# Now, let's look for another element which is known to be in this array'

>>> if 2 in thirdArray: print thirdArray.index(2)
... 
2

# How can  we create 2D arrays in Python? Answer: We use a list of lists

>>> array2DTest = []
>>> array2DTest += [[1,2,3]]
>>> print array2DTest
[[1, 2, 3]]
>>> array2DTest += [[1,4,6]]
>>> print array2DTest
[[1, 2, 3], [1, 4, 6]]
>>> array2DTest[0]
[1, 2, 3]
>>> array2DTest[1]
[1, 4, 6]
>>> array2DTest[1][2]
6
>>> array2DTest[0][0]
1

# A quick look at what zipping a pair of lists does. It returns a list of tuples of (n-th member of first list, n-th member of second list)

>>> zip([1,2,3,4],[5,6,7,8])
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>>