Lists in Python


The sequence is a generic term used to refer to data types which can hold multiple items of data in an orderly fashion. In Python, we have several types of sequences, the following three are most important:

  1. list
  2. tuples
  3. strings

In this chapter, we will discuss list type.

What is a list?

Suppose we want to calculate average marks of 100 students in a class. To accomplish this task, our first step would be to store marks of 100 students by creating 100 variables. So far so good. What if we want to calculate the average marks of 1000 students or more? Should we create 1000 variables? No ! Off course not. This way of solving the problem would be very impractical. What we need is a list.

A list is sequences of multiple items separated by a comma, and enclosed inside square brackets i.e []. The syntax of creating a list is as follows:

Each item that is stored in the list is called an element of a list or simply an element. For example:

This statement creates a list of 4 elements and assigns it to the variable numbers. Note that just like everything else, a list is an object too, of type list. The numbers variable does not store the contents of the list, it only stores a reference to the address where list object is actually stored in the memory.

To print the contents of a list in the Python shell just type the list name.

We can also use print() function to print the list.

A list can contain elements of same or different types.

To create an empty list simply type square brackets without any elements inside it.

We can also create a list using the list() constructor function.

The elements of a list can be a list too.

list5 contains two elements of type list. This type of list is known as a list of list or nested list or multi-dimensional list.

Creating lists using range() function

The range() function can also be used to create long lists. Recall that the range() function returns an object of type iterable (to learn more click here ), all we need to create a list is to pass this iterable object to the list() constructor function as follows:

range(5) generates the following sequence:

The list() function then uses numbers from this sequence to create a list.

Here are some more examples:

Example 1:

Example 2:

List functions

The following table lists some functions, we commonly use while working with lists.

Function Description
len() returns the number of elements in the sequence.
sum() returns the sum of elements in the sequence.
max() returns the element with the greatest value in the sequence.
min() returns the element with the smallest value in the sequence.

Index Operator

Just like strings, the elements in a list are 0 indexed, meaning that the first element is at index 0, second is at 1, third is at 2 and so on. The last valid index will be one less than the length of the list. We use the following syntax to access an element from the list.

where index must be an integer.

For example, the following statement creates a list of 6 elements.

list index

Here list1[0] refers to the element 88, list1[1] refers to 99 and list[5] refers to 9999.

We can also calculate the last valid index of a list using the len() function, as follows:

Trying to access an element beyond the last valid index will result in IndexError.

Just like strings, negative indexes are still valid here. In fact, we can use can negative index on almost all types of sequences in Python.

list negative index

As you can see from the image the last element is at index -1, the second last element is at -2 and so on. The first element is at index -6.

To calculate the index of the first element use len() function as follows:

Lists are Mutable

List are mutable, what this means is that we can modify a list without creating a new list in the process. Consider the following example:

Notice that even after modifying the list the id of the variable list1 remains the same. This indicates that no new list object is created when we assign new element at index 0.

Iterating through elements in a List

To iterate through a list we can use for loop as follows:

In each iteration the variable m is assigned a value from the list. Changing the value of variable m in the loop body doesn’t update the elements in the list. So, this method is commonly used to iterate over list when we don’t need to modify the elements in a list.

To modify elements, we can use a for loop in conjunction with the range() function, as follows:

Although the for loop is a preferred way to iterate over a list, if we want, we can use while loop too. For example:

List Slicing

Slicing operator we discussed in lesson Strings in Python is also available in the list. The only difference is that instead of returning a slice of string, here it returns a slice of a list. It’s is syntax is:

This returns a slice of the list starting from index start to end - 1. Here are some examples:

The start and end indexes are optional, if not specified then start index is 0 and end index is the length of the list. For example:

Membership operator in and not in

Just like strings, we can check whether an element exists in the list or not using in and not in operator. Here are some examples:

List Concatenation

Lists can be joined too using + operator. When operands on both sides are lists, the + operator creates a new list by combing elements from both the lists. For example:

Notice that concatenation doesn’t affect the list1 and list2, their addresses remains the same before and after the concatenation.

Another way to concatenate list is use += operator. The += operator modifies the list instead of creating a new list. Here is an example:

The statement list1 += list2 appends list2 to the end of list1. Notice that the address of list1 is still not changed. Unlike languages like C, C++ Java, where arrays are of fixed size. In Python, lists are dynamically sized. It means that the size of the list grows automatically as needed.

Repetition Operator

We can use * operator with lists too. It’s syntax is:

The * operator replicates the list and then joins them. Here are some examples:

The * operator can also be used as a compound assignment operator *= . The only difference is that instead of creating a new list object, it would update the existing list object.

Comparing Lists

Just like strings, we can compare lists using the relational operators (>, >=, <, <=, !=, ==). List comparison only works when operands involved contains the same type of elements. The process starts off by comparing the elements at index 0 from both lists. The comparison stops only when either the end of the list is reached or corresponding characters in the list are not same.

Consider the following example:

Here are the steps involved in the comparison of list n1 and n2.

Step 1: 1 from n1 is compared with 1 from n2. As they are same, the next two characters are compared.

Step 2: 2 from n2 is compared with 2 from n2. Again they are same, the next two characters are compared.

Step 3: 3 from n1 is compared with 10 from 10. Clearly 3 is smaller than 10. So the comparison n1 > n2 returns False.

Here is another example where elements are strings.

Step 1: "pow" from word_list1 is compared with "power" from word_list2. Clearly "pow" is smaller than "power". At this point, comparison stops because we have found the elements in list which are not same , so comparison word_list1 < word_list2 is true.

List Comprehension

Often times you will need to create lists where each element in the sequence is a result of some operations or each element in the list satisfies some condition. For example, create a sequence of cubes of numbers from 50 to 100. We use list comprehension in situations like these. The syntax of the list comprehension is:

here is how it works:

In each iteration item is assigned a value from the iterable object, then the expression before the for keyword is evaluated; the result of the expression is then used to produce values for the list. The process repeats until there are no more elements left to iterate.

Here is an example:

We can also include an if condition in the list comprehension, as follows:

This works exactly like above the only difference is that the expression before the for keyword is evaluated only when the condition is True.

Here is an example:

List Methods

The list class have many built-in methods which allows us to add an element, remove element, update element and much more. The following table lists some common methods provided by the list class to manipulate lists.

Method Description
appends(item) adds an item to the end of the list.
insert(index, item) inserts an item at the specified index. If index specified is greater than the last valid index, item is added to the end of the list.
index(item) returns the index of the first occurrence of specified item. If the specified item doesn't exists in the list, an exception is raised.
remove(item) removes the first occurrence of the specified item from the list. If the specified item doesn't exists in the list, an exception is raised.
count(item) returns the number of times an item appears in the list.
clear() removes all the element from the list.
sort() sorts the list in ascending order.
reverse() reverse the order of elements in the list.
extends(sequence) appends the elements of the sequence to the end of the list.
pop([index]) removes the element at the specified index and returns that element. If index is not specified, it removes and returns last element from the list. When index is not valid, an exception is raised.

Note that all these methods except count() modify the list object on which it is called.

The following shell session demonstrates list methods in action:

append() method

insert() method

index() method

remove() method

count() method

clear() method

sort() method

reverse() method

extends() method

pop() method

Leave a Comment

%d bloggers like this: