Table of Contents


What is a List

A list in python is a sequence of data of any type or even objects, arranged in order of the sequence numbers starting with 0 and ending at the last (total number-1) number of the sequence.

Lists are flexible, as they can be manipulated, in contrast to a set which is fixed. So, you can add to start or end of a list, you can find a list element by its index number, insert an element at a specific position by giving the index of place to insert it. You will also be able to remove or delete an element, and get it from specific position, and so forth.


Before adding elements to a list, you need to create an empty list. This can be done in two ways: - assign a list to a variable : var = [] and add elements to that variable. - assign empty list to variable using list() function.

Types of list elements

Many lists have a sequence of numbers. The basic way to create a list of sequential numbers is to use the range function.

L = list(range(10))
print(L) ==> [0,1,2,3,4,5,6,7,8,9]

The range function produce elements which starts with 0 and ends with the number before the number given in its argument. You can specify in the range function where to start and where to end, and even how many numbers to skip.

For example, if you need a sequence of each fifth number in the range of numbers between from 100 to 200, you can use this

[100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195]

List elements can be added in different ways, such as giving them as a sequence or read them from a file or database.

list = [1,2,3,4,5] 

Elements in a list can be any object such as strings or a mix strings and numbers :

["one", "two", "three"] =strings
[1, "two", 3.0]     =any object

If the elements are all the same you can multiply a list of basic element by the number of elements :

list = [True]*3
print [None]*10  =empty list of size 10

A list may contain other lists of dictionaries. Lists within list is known as nested list. A dictionary can contain lists, each with a keyword, which is quite useful in data serialisation. Thus, a list may contain a number of dictionaries, each dictionary contains a number of lists, and so on.

Empty nested lists  of given size
print [[]*3]*3  =list of list

Empty list of dictionaries of given size ==>
print [{}]*3    =list of dicts

Data Extraction from a list

The simplest way to extract an element from a list is to indicate its index or its place in the sequence. You should always remember that the index starts with 0, so element number 2 is placed in the third position.

list = [1, 2, 3, 4, 5, 6]
list[2]     =3

In this way, you can get all elements from start of sequence but not including the index.

list = [1, 2, 3, 4, 5, 6]
list[:4] ==> [1, 2, 3, 4]

Also, you are able to get elements in list between indices but not including last

list = [1, 2, 3, 4, 5, 6]
list[1:3] ==> [2, 3]

If you want to get all elements in list from index up to last, start with index of that element and end with None.

list = [1, 2, 3, 4, 5, 6]

If you want to get elements from a list starting from the indices numbered from end of list. precede index with minus sign.

list = [1, 2, 3, 4, 5, 6]
list[:-1] =from start to second last element
list[:-3] ==> [4, 5, 6] =from start to the forth element from the end.

To get elements in list in reverse you need to use two semicolons at start of indexing by -1

list = [1, 2, 3, 4, 5, 6]
list[::-1] ==> [6, 5, 4, 3, 2, 1]

To get all elements in reverse and skip some elements, use two semicolons followed by number of elements to skip, as follows:

list = [1, 2, 3, 4, 5, 6]
list[::-1] ==> not skipping any
list[::-2] ==> [6, 4, 2] skipping every second element
list[::-3] ==> [6, 3] skipping every third element
list[::-4] ==> [6, 2] skipping every fourth element


A list can be sliced and a portion of it extracted using slice function. Slice function will allow getting a slice with some elements skipped. First argument of slice function is index, second is where it ends and third is step or number of elements to skip.

arr = [1, 2, 3, 4, 5, 6]
arr[slice(4)] ==> [1, 2, 3, 4]
=> from start up to but not including index 4 (fifth element)
arr[slice(2,4)] ==> [3, 4]
=> between index 2 and 4(index 4 not included)
arr[slice(1,4,2)]   ==> [2, 4]
=>between index 1 and 4, step 2 (every second element in steps)

To get first element use 0 index, for last element use -1 index, or first n of list elements use index range starting from 0, to get a slice use start and end indices, to get elements from position to end do not give second index in a range.

arr = ['a', 'b', 'c', 'd', 'e', 'f']
arr[0]      ==> first element
arr[-1]     ==> last element
arr[0:3]    ==> first 3 elements
arr[3:]     ==> remaining elements after 3 dropped
arr[2:4]        ==> from third to fourth element

Examine Elements in a List

To get the number of elements in a list use keyword len

browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE']

To check if list is empty, compare it to an empty list.

browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE']
browsers == [] ==> False

To check if list contains a given element use in

browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE']
'IE' in browsers ==> True

Add and Remove Elements in a List

To add elements to end of list, append function is used.

L = [1, 2, 3, 4]
L.append(5) =⇒ add 5 to end of list
L.append(6) =return of function append is None
L =⇒ [1, 2, 3, 4, 5, 6]

You can insert an element at any position in a list by indicating the index of that position. Insert function takes first argument the index of that position and the second is the object to be inserted in the list. insert(index, object)

L = [1, 2, 3, 4]
L.insert(1,2) =⇒ [1, 2, 2, 3, 4]
L.insert(3, [1,2,3,4]) =⇒ [1, 2, 2, [1, 2, 3, 4], 3, 4]

pop function

It remove and return item at index (default last).

L = [1, 2, 3, 4, 5, 6]
R = L.pop() = R equals 6
S = L.pop(3) = S equals 4 =⇒ [1, 2, 3, 5] 4 Removed at index 3

Remove function

The remove function removes the first occurrence of an element in list. It takes the value of the element to be removed from the list.

L = [1, 2, 3, 4, 3, 6]
L.remove(3) = [1, 2, 4, 3, 6] removed first matching element

Del function

Del function removes an element at a given index in a list

L = [1, 2, 4, 3, 6]
del L[2] =⇒ [1, 2, 3, 6]
= del function removed first matching element at index 2

Removing Duplicates

To remove duplicates from a list convert it into a set (set remove duplicates), then convert it back into a list.

a = list(set([ 1, 1, 2, 2, 3, 3, 4, 5 ])) =⇒ [1, 2, 3, 4, 5]
b = list(set(['foo', 0, None, 'bar', 7, 'baz', None])) =⇒ [0, 'bar', 7, 'baz', None, 'foo']
c = list(set([2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556])) =⇒ [0, 2, 5, 6, 8, 9, 556, 123]
d = list(set(["student","sam", "student","george", "teacher","matz"]))

To get the index of given list value use the index function.

[ "a", "b", "c" ] 

Iterate over a list

Iteration is going through the list elements one by one and perform a function on each element. You may iterate over list forward and in reverse.

The most basic function is print, where you want to list each element of the list one by one. You may print them forward or in reverse.

list = [1, 2, 3, 4, 5] 
for x in list : 
  print(x) words = "first second third fourth fifth sixth".split(" ") 

for w in reversed(words): 

The iteration is mainly used by for loop:

for element in list: 

Any function can be used.

map, lambda

Map function helps to iterate over a list and apply a function on each element in the list. The function can be a lambda function. The first argument in Map is the function or lambda and the second is the list to be mapped.

  • Lambda function is created with (lambda variable: use variable in process ).
  • Map function returns modified list.
arr = [1, 2, 3, 4, 5] 
map(lambda a: 2*a, arr) 

Iteration on indices and elements in a list

Sometimes you need to get the index and value of each element in a list. This is particularly useful if you want to print a numbered list of values.

There are two ways in doing this:

  • iterate over indices and elements using a range of length of list:

a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i])

  • iterate using the enumerate function: This allow you to start numbering from 1 rather than 0 by adding a second argument to enumerate 1

a = ['Mary', 'had', 'a', 'little', 'lamb'] for i, e in enumerate(a): print(i, e)

Selection and Filtering elements of a list

If we need to select a group of elements in a list matching certain criteria, you can use if statement or regex match.

List comprehension can make this much easier.

arr = [1, 2, 3, 4, 5, 6] 
[x for x in arr if x % 2 == 0] =[2,4,6]

Selecting element in list matching regex pattern require importing the re module.

import re 
L = ["one", "two", "three", "four", "five", "six"] 
[x for x in L if re.match("^[ft]",x)] 

This gets the words starting with 'f' or ' t'

Compare and interact with more than one list

Dealing with two lists, you may need to compare them, join or concatenate them, add one to end of the other or to the start of the other, find elements which are common in them or elements which are different.

Comparing two lists for equality

a = [ "a", "a", "c" ] 
b = [ "a", "b", "c" ] 
set(a) == set(b)

Joining two lists

Concatenate, join or combine two lists.

a = [ 1, 2, 3 ] 
b = [ 4, 5 ]

common shared elements in two lists

Intersection function return the common and shared elements in two lists.

a = [ 1, 1, 3, 5 ] 
b = [ 1, 2, 3 ] 
set(a).intersection(b) ={1,3} are common in a and b
=> This can be also performed by if statement.
set([e for e in a if e in b]) ={1,3}

Notice that join function does join elements into one continuous string. A separator comes before the join function which takes the list as a parameter.

=> separator.join(list) 
a = ["join", "those", "array", "elements", "with spaces"] 
" ".join(a)

Sorting a list

Sorting numbers in a list is different from sorting strings. Numbers are sorted according to their value. Strings are sorted considering that small letters has higher value than capital letters. To sort elements in a descending order use the reverse keyword argument.

=> list.sort(cmp=None, key=None, reverse=False) 
a = [66.25, 333, 333, 1, 1234.5] 
list = ['A' ,'b' ,'C' , 'd', 'E', 'f']

The key keyword argument can have a function to evaluate elements in a list for sorting.

L = ['A' ,'b' ,'C' , 'd', 'E', 'f'] 
L.sort(key= str.upper) 

Back to Top