Learn Python List by Examples

Tags: , ,
 

Python List is a powerful data structure that you almost need it in every program. Python List can be used to hold a collection of items which can  be any type. In this post, I will use examples to describe how to use python List. 

Python List Declaration

It is easy to create a python list object. The following code declare a List L and initialize it with 4 values.

In [1]:
L = [1, 2, 'Jim', ('hello, word')]
print L
 
[1, 2, 'Jim', 'hello, word']
 

Data look up in python List

We can locate the elements in the List by index. Please be noted, like C and Java, python List is also 0-index based.

In the following example, we use L[1] to pick up the value at index 1. 

In [2]:
print L[1]
 
2
 

Update the data in Python List

We can simply set new value to a python list using  the syntax L[index] = new_value

For example, by setting L[2] = 22, the third element in the list is updated.

In [3]:
L[2] = 22
print L
 
[1, 2, 22, 'hello, word']
 

Python List IndexError

If the index is out of range, you will get IndexError. To prevent this error, we can first check whether the index is less than the length of the List.

The python list IndexError Example:

In [4]:
print L[5]
 
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-af37846611f3> in <module>()
----> 1 print L[5]

IndexError: list index out of range
 
To prevent python list indexError, we can check whether the index is less the length. The len() method is used to get the length or size of a python list object. 
 
In [5]:
if 5 < len(L):
    print L[5]
else:
    print '5 is outof index'
 
5 is outof index
 

In the following sections, I will describe some advanced topics of python List, such as slicing, iteration, use python List as a stack, use python List as a queue. 

Python List Slicing

The syntax for python List slicing is L[m:n], which return L[m], ... L[n - 1], so L[m:m] is empty. What happend if n is larger than the length of the list? In this case, It is equivalent to L[m:], which means all the elements after index m (inclusive) are returned. See the following example.

In [6]:
L = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print L[3:6] # pick up A[3], A[4], A[5]
 
[3, 4, 5]
In [7]:
print L[3:3] # this will be empty
 
[]
In [8]:
print L[3:100]
print L[3:]
 
[3, 4, 5, 6, 7, 8]
[3, 4, 5, 6, 7, 8]
 

Python List Iteration

There are two methods to iterate a python List.

  1. use for loop
  2. use while loop See the following example.
In [9]:
for a in L:
    print a
 
0
1
2
3
4
5
6
7
8
In [10]:
index = 0
while index < len(L):
    print L[index]
    index += 1
 
0
1
2
3
4
5
6
7
8
 

Python List Comprehension

Comprehension is very helpful in python, as it can help you write clean, easy to read code. You can just consider it as a compact for loop. A typical use case of python comprehension is to generate a list from another generator. See the following examples,:

  1. generate a python list with 10 zeros
  2. generate a python list of integers that are square of 0 to 10.
In [11]:
zeros = [0 for _ in range(10)]
print zeros
 
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
In [12]:
square = [i * i for i in range(10)]
print square
 
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
 

Use Python List as a stack

Stack is a popular data structure to solve many different problems such as deep first search, Tree traverse. We can use Python List as a stack by following the FILO(First in, last out) property. To use List as a stack, we can use the two methods:

  1. append(), which add an element at the end of the list
  2. pop(), which remove an element at the end of the list
In [13]:
stack = [1, 2, 3]
print stack
stack.append(4)
print stack
stack.append(5)
print stack
pick = stack.pop()
print pick
print stack
 
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
5
[1, 2, 3, 4]
In [14]:
print stack.pop()
print stack
 
4
[1, 2, 3]
 

Use Python List as Queue

Queue is another important data structure to solve many problems such as Bread First Search, Level by level tree traverse.

We can use python List as a queue by following the FIFO (first in first out) property. TO use List as a queue, we can use the two methods:

  1. pop(0), which remove the first item of the List
  2. append(), which append the item in the end of the list
In [15]:
queue = [1, 2, 3]
queue.append(4)
print queue
 
[1, 2, 3, 4]
In [16]:
print queue.pop(0)
print queue
 
1
[2, 3, 4]
In [17]:
print queue.pop(0)
print queue
 
2
[3, 4]
 

Do not use Python List as a queue

Be careful, appends and pops from the end of list are fast, but pops from the beginning of List is slow. To implement a queue, the collections.deque class should be used, which is deigned to enable fast append and remove from both ends.

In [21]:
from collections import deque
q = deque([1, 2, 3])
q.append(4)
print q
 
deque([1, 2, 3, 4])
In [22]:
pick = q.popleft()
print pick
print q
 
1
deque([2, 3, 4])
In [23]:
pick = q.popleft()
print pick
print q
 
2
deque([3, 4])