Learning Management Platform for Written Tutorial Series.

Python 3 Lists - Create and perform operations on lists

Python 3 Lists - Create and perform operations on lists

Python Lists

A list is essentially an array of items. Think of a list as a variable that contains multiple values. Lists can contain strings, integers, floats, dictionaries, tuples and even lists. They are very useful when we want to store related data in a single variable. We access items in the list using index numbers, we can also add and remove items from the list.

Topics to be covered

In this lesson, we will cover the following topics

  • How to create lists in python
  • Accessing items in a list
  • List slicing in python
  • Adding items to a list in python
  • Removing items from a list in python
  • List Comprehension
  • Python List Operations

How to create lists in python

In this section, we will create a list that contains names of countries in East Africa.

east_africa = ['Tanzania','Kenya','Uganda','Rwanda','Burundi']

print(f'Countries that are in east africa include')

for country in east_africa:
    print(country)

HERE,

  • east_africa = [...] defines a list that contains countries that are in east Africa. Square [] brackets are used to defines lists in python and we separate the items in a list using commas ,.
  • for country in east_africa: uses the for loop to iterate through each element in the list and prints it out in the console

Executing the above code produces the following results.

Tanzania
Kenya
Uganda
Rwanda
Burundi

Accessing items in a list

In the above example, we used a for loop to access the items in a list. In this section, we will use index numbers to access items in a list.

cars = ['Toyoto','BMW','Benz','Ford']

print (cars[0])

HERE,

  • cars = ['Toyoto','BMW','Benz','Ford'] defines a list variables called cars
  • print (cars[0]) accesses the first item in our list using the index number 0 and prints it out in the console. Note: we starting counting elements from 0 and not 1.

Executing the above code produces the following result

Toyoto

Using the knowledge that you have gained, can you try to access the third item in the list and share your solution in the comments section.

List slicing in python

List slicing allows us to extract a portion of the list as determined by the index numbers. Let's create a list that contains names of moves like so.

movies = ['Couples Retreat','Horrible Bosses','40 Year Old Virgin','Last Friday','Shaka Zulu']

print(movies[0:2])

HERE,

  • movies = [...] defines an array variable called movies.
  • movies[0:2] extracts 2 items from the movies list starting from index 0.

Executing the above code produces the following results.

['Couples Retreat', 'Horrible Bosses']

Adding items to a list in python

In this section, we will look at how we can add more items to a list that is either empty or we have already added items to it. Let's now look at a practical example.

genres = ['Heavy Metal','Symphonic Metal']

genres.append('Black Metal')

print(genres)

HERE,

  • genres = ['Heavy Metal','Symphonic Metal'] defines a list that contains genres of rock music.
  • genres.append('Black Metal') calls the append method of the list passing in Black Metal as the argument. This appends the item Black Metal to the end of the list.
  • print(genres) prints all the items in the list.

Executing the above code produces the following results.

genres = ['Heavy Metal','Symphonic Metal']

genres.append('Black Metal')

print(genres)

We can also add items to a list using the insert method. The insert method allows you to select the index number where you want to insert the item.

genres.insert(0,'Death Metal')

HERE,

  • The above code inserts the item Death Metal to the list genres at index number 0. The item that was at index 0 is pushed to 1 , 1 to 2 and so on and so fourth.

Removing items from a list in python

It is also possible to remove items from a list like so

books = ['Think & Grow Rich','The Richest Man in Babylon','Will Power','The Age of Reason']

books.pop(3)

print(books)

HERE,

  • books = ['Think & Grow Rich','The Richest Man in Babylon','Will Power','The Age of Reason'] defines a list that stores book title.
  • books.pop(3) removes the item at index 3
  • print(books) prints the contents of the books variable

Executing the above code produces the following results

['Think & Grow Rich', 'The Richest Man in Babylon', 'Will Power']

Note: the item The Age of Reason is missing from the above results. This is because we removed it using the pop method.

List Comprehension

List comprehensions allow us to create new lists from an existing list using a for loop and if necessary an if statement using a simple expression. Let's explain this using a simple practical example.

Consider the following code

import math

squares = [1,4,9,16,25,36]

square_roots = []

for number in squares:
    square_roots.append(math.sqrt(number))

print(square_roots)

HERE,

  • squares = [1,4,9,16,25,36] defines a list that contains square numbers
  • square_roots = [] defines an empty list that will store square roots of the square number
  • for number in squares: loops through our list and assign the value of each iteration number to the variable number
  • square_roots.append(math.sqrt(number)) appends the square root of the square number to the square_numbers variable
  • print(square_roots) prints out the square roots of our square numbers.

Executing the above code produces the following results

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

Now, let's see how a list comprehension can simplify the above code

The syntax for list expressions is as follows

new_list = [expression for i in list]

HERE,

  • expression is the processing that you want to perform on the item as it is extracted. For example, math.sqrt(number) can be used as an expression. You can also perform expressions such as i * 2 etc.
  • for... starts the for loop within our comprehension lit that will iterate through each item in our list
  • new_list defines a variable that will contain the new return that our comprehension will return.

Let's now rewrite the above example using a list comprehension like so.

import math

squares = [1,4,9,16,25,36]

roots = [math.sqrt(number) for number in squares]

print(roots)

HERE,

  • roots = [math.sqrt(number) for number in squares] creates a new list root using a comprehension list. math.sqrt(number) is the expression for the iteration for number in squares

Executing the above code produces the following results

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

If statement in a comprehension list

Comprehension lists can also contain an if statement to filter out the numbers that we want to use in our expression. The syntax is as follows

new_list = [expression for i in list if condition == true]

HERE,

  • new_list defines the variable that will contain our new list returned by our list comprehension
  • expression defines the expression that we want to perform while creating our new list.
  • for i in list iterates through our existing list
  • if condition == true imposes a condition on our comprehension. The expression is only executed if the condition is true.

Let's now look at a practical example. Suppose we have a list of numbers and we want to create a new list that contains only even numbers. We can do it like so.

numbers = list(range(11))

even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)

HERE,

  • numbers = list(range(11)) uses the range function to generate a list of numbers from 0 to 10.
  • even_numbers = [number for number in numbers if number % 2 == 0] uses a comprehension list to return the value of the variable number if the condition if number % 2 == 0 is true.
  • print(even_numbers) prints out our new list.

Executing the above code produces the following results

[0, 2, 4, 6, 8, 10]

Python List Methods

In this section, we will look at the some of the built-in functions that come with list objects. We have actually already looked at some of the list methods in the above examples. We called the append,insert, and pop methods in the above examples.

Let's look at some of the popular methods that we can call on operations.

Count number of items in a list in python

Let's say we want to get the number of items in a list, we can do it like so.

apps = ['Browser','Email','News','Calculator']

print(f'The list variable apps that {len(apps)} items')

HERE,

  • len(apps) passes the variable apps as the argument to the built-in function len that returns the number of items in our list

Executing the above code produces the following results

The list variable apps that 4 items

Reversing a list in python

We will create a variable that lists applications, print the original list, reverse it then print the reversed list.

apps = ['Browser','Email','News','Calculator']

print('the original list order is')
print(apps)
apps.reverse()
print('the reversed list order is')
print(apps)

HERE,

  • apps = ['Browser','Email','News','Calculator'] defines a list variable apps
  • print(apps) prints the original list
  • apps.reverse() calls the reverse method which reverses the order of the items in the list.
  • print(apps) prints out the reversed list

Executing the above code produces the following results.

the original list order is
['Browser', 'Email', 'News', 'Calculator']
the reversed list order is
['Calculator', 'News', 'Email', 'Browser']

Sorting items in a list in python

We will work with our apps list and sort the items in it in alphabetical order

apps = ['Browser','Email','News','Calculator']

print('the original list order is')
print(apps)
apps.sort()
print('the sorted list order is')
print(apps)

HERE,

  • apps.sort() sorts the items in our list in alphabetical order

Executing the above code produces the following results.

the original list order is
['Browser', 'Email', 'News', 'Calculator']
the sorted list order is
['Browser', 'Calculator', 'Email', 'News']

Let's say we want to sort our list in descending order. We can do it like so.

apps = ['Browser','Email','News','Calculator']

print('the original list order is')
print(apps)
apps.sort(reverse=True)
print('the sorted list in descending order is')
print(apps)

HERE,

  • apps.sort(reverse=True) sorts our list in descending order because of the reverse parameter which we passed in the argument of True.

Executing the above code produces the following results.

the original list order is
['Browser', 'Email', 'News', 'Calculator']
the sorted list in descending order is
['News', 'Email', 'Calculator', 'Browser']

Summing all numbers in a list

In this example, we will create a list of numbers from 0 to 10 then sum of them using the sum function

numbers = list(range(11))

summation = sum(numbers)

print(f'the sum of all the numbers in our list is {summation}')

HERE,

  • numbers = list(range(11)) creates a numbers variables that contains numbers from 0 to 10
  • summation = sum(numbers) calls the sum function passing in our numbers list variable as an argument.

Executing the above code produces the following results.

the sum of all the numbers in our list is 55

How to find the minimum value in a list in python

We will work with the above example to find the minimum number in our list

numbers = list(range(11))

print(f'the minimum number in our list is {min(numbers)}')

HERE,

  • min(numbers) uses the min function to find the lowest value in our list.

How to find the maximum value in a list in python

We can use the max function to find the maximum value in a list like so

numbers = list(range(11))

print(f'the maximum number in our list is {max(numbers)}')

HERE,

  • max(numbers) uses the max function to the largest value in our list.

How to filter a list in python

Let's say we have a list of numbers from 0 to 10 and we would like to extract even numbers from our list, we can do it like so.

numbers = list(range(11))

def get_even_numbers(number):
    return number % 2 == 0

even_numbers = filter(get_even_numbers, numbers)

print(list(even_numbers))

HERE,

  • numbers = list(range(11)) generates a list of numbers using the range function
  • def get_even_numbers(number): defines a method that checks if a number if divisible by 2. If yes it returns True else it returns False
  • even_numbers = filter(get_even_numbers, numbers) calls the filter function that accepts two parameters. The first one is a function that filters the list the second the list to be filtered

Executing the above code produces the following results.

[0, 2, 4, 6, 8, 10]

Alternatively, we can use a lambda function to filter a list like so

numbers = list(range(11))

e_numbers = filter(lambda x: x % 2 == 0,numbers)

print(list(e_numbers))

HERE,

  • e_numbers = filter(lambda x: x % 2 == 0,numbers) calls the filter function using a lambda function lambda x: x % 2 == 0 and the numbers variables as the second argument.

The above code produces the following results

[0, 2, 4, 6, 8, 10]

The lambda way is easier and common when working with list filters.

Summary

A list is an array of items stored in a single variable name. The items are indexed from 0 to the total number of items in a list minus 1. For example, a list with 5 items has 0 as the first index and 5 - 1 which gives us 4 as the last index number. A list is an object so it has methods that perform specific tasks withut requiring special custom code. You can ue a for loop to iteratethrough a list.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...