Python Tutorial

Python List Tutorial [ The Complete Guide with Examples].

In this python list tutorial, you will learn everything you will find in any good PDF python programming book. You will learn the methods to manipulate list in an easy to understand way.

I will also teach you also some cool python codes to solve real-life problems using the concept of python list.

But First,

The Basics of Python list.

A list is a set of data or items, arranged in an order. In this tutorial, I will use items and elements interchangeably. An example of a list in life is a grocery list for shopping or a list of newly admitted students.

So,

We now know what a list is, but it is interesting to know that in python, a list and tuple have a similar structure.

A tuple and a list have items which are separated by a comma but the items of a tuple are enclosed in a bracket() but that of a list are enclosed in a square bracket.

Take a look at examples of a tuple below:

Take a look at examples of python lists below:

In python, a list can contain any element which could be a string, an integer or even other lists, hence list is heterogeneous in nature.

DIFFERENCE BETWEEN LIST AND TUPLE.

I mentioned earlier that a list and tuple have a similar structure.

The major difference between list and tuple is that a list is mutable and a tuple is immutable.

Mutable means that the structure or sequence and contents(elements) of a list can be accessed, changed or manipulated. Lists are objects and have methods to modify the list without creating a new list. It is important to note that all these methods modify the list instead of creating a new list.

Immutable means that the structure and contents of a tuple can not be changed but can be accessed.

In simple words for you to understand,

List items can be changed, hence it is mutable.

But,

A tuple is immutable because it’s items can not be changed.

If you are like me that always forgets the difference between list and tuple.
 
Here’s a tip for you.

HOW TO CREATE A PYTHON LIST.

let me show you a quick way you can create a list of integers using the range and list function. 


NOTE:

The range function, range(x,y) returns a sequence of integers starting from the first integer x and stops at y-1. The split() changes a string to a list.

So now that you can create a python list, let me show you how to access the items in a list so that we can modify them.

Python list can be created using python list comprehension.

This method is short and very easy. The code below is how to create a list of random numbers and even numbers using python list comprehension.

Note:

The % operator returns the remainder of a division.


INDEXING PYTHON LIST.

In python, index specifies the position of an element in a list. The index value of the first element in a list is 0 and the last element is one less the number of elements in the list.
Take a look:

An example of a list showing index.

The index method returns only one item in the list. Square brackets are used to access a list.

Note:
  • The len function returns the number of items in a list.
  • The index value or position -1 returns the last item in a list.

Use L.index(item) to return the position of an item in a list.

LIST SLICING IN PYTHON.

 Remember that the index method returns only one item in a list. Slicing returns more than one item in a list, it returns a range of elements in the list.
 
A simple analogy of slicing is when you slice bread into two, you take a part discarding the other. In slicing, we are only interested in one part or a range of elements in a list, the other elements are discarded.
 
Create a list of science subjects and another list of integers from 1-10

To slice any of the above lists in python, use subjects[start:stop] or x[start:stop] respectively. 

The start is the index value of the first item in the slice and the stop is the index value that slicing stops. The result of the slicing is a list containing elements from the beginning of the slice to the end.


If you are interested in all the elements in a list, 


use subjects[:] or x[:]

From the list I created above, let me show you how to slice.
 

FINDING ELEMENTS IN LISTS WITH THE IN OPERATOR.
 You can have a list containing a lot of elements and to know if an element is present in the list you use the in operator.
 
A True value is returned if the item is in the list and a False value is returned if the item is not in the list.

 

REPLACING ELEMENTS IN A LIST.

The subscript operator is used to assign a new item at the specified index, hence replacing the old item at that specified index. A new list is not created but only modified. This method won’t return the modified list unless you call your list.

Take a look:

USING SLICING TO REPLACE A RANGE OF ITEMS IN A LIST.

You have learned how to slice a list. Using slicing, we can replace a range of items with another range of items in a list.

Take a look at the code below.



 

You have learned how to replace an element in a list, let solve a problem that will require your knowledge in replacing items in a list.

 

PYTHON LIST PROJECT 1:

Write a python script to replace each integer in the list below with its square root.
 
[289,256,225,196,169,144]
 

SOLUTION 1:

  • First import math module
  • Assign your list to a variable(square_numbers)
  • Assign zero to index(remember that Python assigns zero to the first item on a list)
  • Use a while loop(conditional statement) as I used below.
 

 

SOLUTION 2: Using for loop.(Remember to indent your code properly.)
 

 

 

Solution 3: using Python list comprehension in just three lines of code.


 


PYTHON LIST PROJECT 2:

Write a python script to convert a sentence into a list and capitalize each word.
 
The sentence is: python list tutorial with simple projects.
 
Solution:
 

 
 
The string method split() returns a list of the words and S.upper() return a copy of S converted to uppercase. If there is any error in your program, remember to properly indent your code. 
 
Note: The string method strip() removes the leading and trailing whitespace. 
 
Take a look at the code below.
 

 

PYTHON LIST METHODS

 

INSERT

L.insert(index,item)— This list method inserts an item before the index specified. It doesn’t return the list unless you call it.

Take a look at the code below.


 

APPEND

L.append(item)— This method adds a new item to the end of a list. It does not return the list but modifies it. To see your updated list, you have to call your list. 

Take a look at the code below.


 

EXTEND

L.extend(my_list)— This method does the same work of the list concatenation operator(+). It takes a list and appends it to another list without returning the list but just updating it.


Take a look at the code below.


 


REMOVE

L.remove(item)— If you don’t know the index of an item in a list and you want it removed, you will have to use this method. It removes one item at a time. 
 
 Take a look at the code below.
 

To remove more than one item in a list with slicing, use del statement.

Take a look at the code below.

 

REVERSE

L.reverse()– It reverses the items in a list.


 


SORT

 
  • First, create random numbers between the range of 2-21. Don’t expect the result I got. Your computer will give you another set of random numbers.


 


  • Copy your result and create a list object with the name random_number. Don’t forget to remove the trailing comma.


 

Now we have a list that’s not in any particular order and we may need to sort the list in ascending order to find median or do some statistical analysis. 

How can we sort a list in python?

Use L.sort() method.

Take a look at the code below.

NOTE: 

  • Using L.sort() only arranges items in ascending order.
  •  Python provides two arguments which are optional. 
  • The two arguments are key and reverse.
  • Assign True to reverse, to sort a list in reverse.
  • Assign len to key, to sort a list of words according to their length.
Take a good look at the code below.
 

 
 

COUNT

L.count(item)— This method returns the number of times an object(item) occurs in a list.


CLEAR

L.clear()– This method removes all items in a list.

 

POP

L.pop(index)– It removes and returns an item at the index specified. If no index is specified, the last item would be returned and removed from the list

Take a look at the code below:

 


COPYING ITEMS IN A LIST.

An analysis may be performed on a list and you may need to keep the original copy of the list for future use. When copying a list a beginner should be aware of aliasing and side effects.

ALIASING AND SIDE EFFECTS

 

If you are a beginner and I asked you to copy a list, you may likely do it like this.

 
Take a good look at the code below and write down what you observe. If after looking and you didn’t observe anything, try running the code.
 
 
This is what I did and observed at the end.
    1. I created a list object old_list
    2. I then assigned the old_list to new_list
    3. To me, I’ve made a copy of the old_list
    4. I then modified my new_list with mutators(insert, remove and clear)
    5. Then I called the old_list and new_list. I observed something wrong.
    6. I observed that all the modification I made to new_list was also made to old_list.

 Let me quickly explain further.

 
When I created a list object, old_list and assigned it to another list object, new_list. I didn’t actually make a copy of old_list, instead, I created a single list object. old_list and new_list are referring to the same list object in my computer memory. The phenomenon in which as I modified new_list and old_list was also modified is known as a side effect.

The diagram below is what we want to achieve when copying a list. We don’t want Old_list and New_list to be stored in the same memory space. 

python list tutorial old list new list - Python List Tutorial [ The Complete Guide with Examples].


Please the ‘tuts’ represents ‘tutorial’
You can copy a list using the following methods.
 
L.copy() –
I recommend this method as it’s very easy to use. You will observe that aliasing and side effect didn’t occur.
Using slicing

 

Before we do more cool python projects,

let me tell you some built-in functions we can use with a list.

Built-in functions Description
len(my_list) Returns the number of items in my_list.
max(my_list) Returns the item with the largest value
in my_list.  
min(my_list) Returns the item with the smallest value
in my_list.  
sum(my_list) Returns the sum of elements my_list.

For better understanding, take a look at the code below.


 

 

Let’s look at one more built-in function we can work with list.

enumerate()

If you want to return the index( that’s the position of an item in a list) and the item in that index, you can use a python list built-in function known as enumerate()

To illustrate this,

I will use some constants in science such as:

  1. Boltzmann constant ,k = 1.3805 E-23
  2. Planck’s constant,h = 6.6625E-34
  3. Velocity of light in vacuum,c = 2.998E8

Here is the python script to illustrate enumerate()

 

PYTHON LIST PROJECT 3:

Write a python script to find the mean(average) of the following set of numbers  5, 4, 3, 6, 6, 5, 2, 8.

I will show two solutions to this problem, if you figure out any other way, please share your code via the comment box.

SOLUTION 1: 

This solution is for does who don’t have a statistics module in their version of python(2.x)


SOLUTION 2:

This solution is for those whose version of python(3.x). You will ultilize the statistics module. I recommend the first solution to a beginner because in real life, some problems will require you developing your alogrithm.

Python list project 4:

Write a python script to determine the median of the set of data 5, 4, 3, 6, 6, 5, 2, 8
 
Before we proceed,
let me remind you of some facts you need to know.
 
  1. The list has to be sorted in ascending order first.
  2. If the number of digits is odd, the median is the digit at the middle position of the list.
  3. If the number of digits is even, the median is the average of the two digits at the middle position of the list.
SOLUTION 1:

SOLUTION 2:

 

PYTHON LIST PROJECT 5:

Write a python script to sort this list in ascending order.
[13, 18, 13, 18, 18, 12, 15, 13, 12, 14, 20]
Don’t use sort()

SOLUTION:
 

 
 

PYTHON LIST PROJECT 6:

Write a python script to find the mode of the set of these numbers,
 
2, 5, 10, 9, 10, 10, 2, 10, 7, 7, 9, 1, 6, 4, 3, 7, 3, 10, 7, 6.
 
But first, let me remind you that mode  is the most frequently
occurring number in a set of numbers.
 
 
SOLUTION:
 
 

 
 
In the program above, 
 
our variable ‘data’ stores the list of integers. I then created an empty list with the variable ‘x’.
 
The for loop iterates the items in the list(data)
 
x.append(data.count(item)- Using the list methods count and append, this code adds the count(number of times an item occurs in data) to the empty list we created.
 
At this point, if you print x you will get a list of a count of each item in data. Take a look:
 

 
So, let me break down the code below for you to understand what it does.
 
print(‘mode:’,data[x.index(max(x))]) –  
 
max– it selects the maximum value of x.(Recall  that x is now  a list of a count of each item in data)
 
index– it returns the position(index) of the maximum value of x. The index or position returned is 2.
 
It is interesting to note:
  1. 5 occupies five positions in the list x.
  2. The list method index returns the first position 5 occupies which is 2.
If you’re really following, you must have observed from what I noted last, that there is a flaw in our program which I’ll tell you later.
 
data[…..]: This returns the item in data that has the highest count which is the maximum value of x.
 
print(): This outputs our result.
 
Like I said, 
 
there is a flaw in our program.
 
Try running this program for the set of the following numbers:
7, 2, 3, 7, 3, 8, 6, 1, 1, 9.
 
Your result will be 7.
 
But, 7, 3 and 1 occur the same number of times, therefore we don’t  have any most occurring number, hence, our result is wrong.
 
Even if we try using the solution below we will get an error message:

In another tutorial, I’ll tell you how you can solve this problem.

 
Who told you that python can’t be used to create SEO tools?
 

Let’s take a look at the next project.

 

PYTHON PROJECT 7:

Write a python script to determine the major keyword in these sentences;
 
Why not learn python today? As a python programmer, I recommend python to everyone who is interested in programming. Python is a multi-purpose language and for me, Python is the best.
 
SOLUTION:


 
 
NOTE:
The solutions to Project 5 and 6 are not the perfect solutions under some specific circumstances so I won’t advise anyone to use them for a real life scenario. The solutions are just for you to understand list and how to use list methods (mutators) and other built-in functions in python can be used to manipulate items in a list.

Challenge yourself in python list or you can go to StackOverflow and try and solve problems people are having in python list. It will help you to become a better python programmer.

The Importance of List.

I want to write a Python program to store my year4 courses I did in my first semester  which were

  1. Eng401
  2. Eng402
  3. Che417
  4. Che413
  5. Che415

If you’re  a beginner you would probably write your Python script like this:

Let’s save this program as my_courses.py

Creating many variables to store my courses is what I did in the Python script above.

I won’t blame you because that was what I did before I understood Python list.

Let’s run our program

 

In the above program, I wrote 5 courses, but I actually did 7 courses.

How then can I store the remaining 2 courses?

I use List.

A list makes my work easier.

Let me show you an elegant way of doing this with a list:

Let’s save this program as my_courses.py2

Let’s now run our Python program (my_courses.py2)

By using the data structure list, I have made my program flexible because I can now use Python list mutators to manipulate my list of courses.

I have come to the end of this tutorial. If you learned a lot, please kindly share.

If you’re having problem with python string, I recommend you read
Best Of Python Strings, Functions And Examples

Feel feel to comment, if you have any question or contribution.

Graphic design credit to Tutorial Graphics.

copyscape banner blue 200x25 - Python List Tutorial [ The Complete Guide with Examples].

About the author

Rapture Godson

I am Godson; the brain behind Cool Python Codes. On this blog, I will make Python much fun and very practical. My up-to-date tutorials are based on my studies and they are very easy for you to understand.

23 Comments

Leave a Comment