Python Lesson 08 – Lists

In this tutorial you’ll learn what lists are. In computer science, a list is a collection of items placed in a particular order. In python, a list can contain mixed types. This tutorial introduces you the collections in Python. Basically, collections types are specialized data structures which include: lists, tuples, dictionaries and sets.

 

List Syntax

In python, we can define a list using square brackets.


my_list = [] # define an empty list

numbers = [1, 2, 3, 4, 5, 6] # define a list of six items

names = ["John", "Jack", "George"] # define a list of three strings

print(numbers) # print the list
print(names) # print the list

As you can note, a list is basically a way to store multiple items in a single variable.

Python lists are ordered: the first item is at position 0, the second item is at position 1, and so on. The concept of position leads us to talk about indexing. In Python, it is possibile to access any item in a list by referring to its position, or index to put it better.

 

Indexing

Python provides ways to access the individual items in a list. In Python, indexing starts from 0 (other programming languages do the same). It means that the first item of a list has the index 0.


mixed_list = [1, "Hello", True, 2.5] # list containing different types

first_item = mixed_list[0] # number 1
second_item = mixed_list[1] # "Hello" string
third_item = mixed_list[2] # True boolean

# and so on...

The example above shows as a list can contain different data types. Then, it is useful to understand how to access the items (taken individually). Generally, the syntax to access the items is nameofthelist[index], as the example above shows. If you’re wondering if it is possible to access multiple items simultaneously, the answer is yes. The concept of slicing serves our purpose.


numbers = [3, 4, 10, 2, 1, 6, 9]

first_two_items = numbers[0:2] # 0 can be omitted, 3 and 4 are selected
items = numbers[2:5] # 10, 2, 1 are selected
last_item = numbers[-1] # the last item, 9 in our case

In the example above, at line 3 we access the first two elements of our list. The colon separates the starting index from the ending index (the latter not included). This means that, in our case, the elements at the first position (index 0) and at the second position (index 1) will be selected. Index 2 is not included. Therefore, the output will be 3, 4. Note that, in this specific case, 0 can be omitted: if we don’t specify the starting index, Python assumes it to be 0.

At line 4, we select the elements with index 2, 3 and 4, for the same reasons just explained.

Finally, at line 5 we select the last element of our list using a negative number. If we specify a negative number as the index, Python starts to index the list from right to left. Therefore, -1 refers to the first item considering the list from right to left. Similarly, -2 refers to the second item considering the list from right to left (the second to last in the normal logic), and so on…

We can include a third parameter in the square brackets, which is a sort of step. Let’s give an example:


numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[0:10:2]) # output: 0, 2, 4, 6, 8

We’re telling our program: “Start from 0, continue until 10 (not included) and move forward in steps of two”. In this way, Python starts selecting index 0 and, then, immediately moves to index 2 (which refers to number 2 in our case). Feel free to change the step value and observe the different outcomes.

Note: the process of slicing (extracting a portion of a list based on indexing syntax) always returns a list, in terms of data types, containing the selected items. Instead, the simple indexing (that consists of accessing the single item in a list) returns the specific data type of that item.

 

List Methods

List methods are built-in functions that you can use to interact with lists. In this section, we’ll discuss the most used list methods.


my_list = [0, 1, 2, 3, 4, 5]

my_list.append(6) # add 6 at the end of the list
print(my_list) # Output: [0, 1, 2, 3, 4, 5, 6]

my_list.insert(2, 10) # insert 10 at index 2
print(my_list) # Output: [0, 1, 10, 2, 3, 4, 5, 6]

my_list.remove(4) # 4 will be removed
print(my_list) # Output: [0, 1, 10, 2, 3, 5, 6]

my_list.extend([1,2,3]) # add all the items from the list passed as parameter
print(my_list) # Output: [0, 1, 10, 2, 3, 5, 6, 1, 2, 3]

my_list.clear() # remove all elements from the list
print(my_list) # Output: []

By using these methods, you can easily and efficiently handle operations (like adding or removing specific elements) on lists.

 

List Functions

List functions are built-in Python functions that can be used with lists as arguments. These functions are not specific to lists and can often work with other iterable objects (such as tuples or sets, that we haven’t talked about yet). Here are examples of list functions.


my_list = [4, 1, 2, 10, 9, 3]

number_of_elements = len(my_list) # returns the length of the list: Output 6

total = sum(my_list) # returns the sum of all elements in the list: Output 29

min_value, max_value = min(my_list), max(my_list) # the smallest value and the largest value, respectively

sorted_list = sorted(my_list) # returns the sorted list (it doesn't modify the original list)
print(sorted_list) # Output: [1, 2, 3, 4, 9, 10]

These functions are examples of list functions. At line 3, the len() function returns the number of elements in the list (i.e., 6). At line 5, the sum() function returns the sum of all elements in the list. At line 7, we use both the min() function and max() function. As you can see, we assign two values to different variables in one line, a process known as multiple assignment. Finally, at line 9 we apply the sorted() function to obtain a sorted list without modifying the original one. The sorted() function can also be applied to lists containing string values. In that case, the list will be sorted alphabetically.

 

List Iteration

List iteration refers to the process of accessing and performing operations on each element of a list. This is a very common task when working with lists. Let’s explore the most common ways to iterate through a list.


my_list = ['banana', 'orange' , 'apple', 'cherry'] # define a list of strings

for x in my_list: # for each element in my_list
    print(x) # print the element

In the example above, we iterate through my_list using the for loop. The code above will print each list element in a new line. Run the code to actually see the output.


my_list = [4, 5, 6, 7, 8]

for i in range(len(my_list)):
    print(f"Index {i}: {my_list[i]}")

# Output:

# Index 0: 4
# Index 1: 5
# Index 2: 6
# Index 3: 7
# Index 4: 8

In the example above, we use the range()  function to iterate through the list. Additionally, we use list indices to access each element. This is very useful when you need the index of each item while iterating through a list.

 

Exercise

To conclude, let’s look at a basic exercise to reinforce the concepts about the lists that we’ve learned so far. Given a list of integers, calculate the mean value of all the elements in the list. Note: the sum() function is not allowed.


numbers = [2, 30, 15, 19, 3, 65] # define the list using random integers

my_sum = 0 # instantiate the sum value t0 0 at the starting point

for x in numbers: # for each element in the list
    my_sum += x # my_sum is incremented by the value of that specific element

how_many_elements = len(numbers) # length of the list

mean_value = round(my_sum / how_many_elements, 2) # round the result to two decimal places

print(f"The mean value of {numbers} is {mean_value}")

In the example above, the code from line 3 to line 6 (both inclusive) can be directly solved using the len() function. However, the purpose of this exercise is to encourage you to think of an alternative way for calculating the sum of the list. Using a  for loop to iterate through the list represents one such alternative solution. At line 10, we use the round() function to round the result to a specified precision in decimal places. In this specific case, the result is rounded to two decimal places by passing the value 2 to the function.

Note: in computer programming, there are often many different ways to solve a problem or perform a task. Feel free to develop your own solutions and programming style through practice.