📓 About This Tutorial

This webpage is a static view of an interactive Jupyter Notebook tutorial. To get the full interactive experience where you can run Python code, modify examples and complete exercises, click the "Open in Colab" button. This will access the Google Colab notebook from a GitHub repository github.com/dchappell2/Computational-Physics and open it in Google Colab. You will need a Google account if you want to open it in Colab.

Note: You can download a pdf of the lecture slides for this chapter here: Chapter 4 slides

Chapter 4 - Lists

Goals

4.0 Overview

Base Python provides many ways of organizing collections of items including lists, tuples, sets and dictionaries. Python libraries extend these options to numpy arrays, padas dataframes and more. The options can be a bit overwhelming at first. We'll focus on Lists in this chapter and NumPy arrays in Chapter 8.

Lists are one of the most commonly used objects in Python, even though they are not the most effecient for intensive computational work. Many of the concepts developed in this chapter can be direclty transferred to other objects such as NumPy arrays discussed later in this tutorial.

4.1 A list stores many values in a single structure

my_list = [10, 20, 30, "hello", True, 60]
print('my_list contains these items:  ',my_list)

4.2 Use the function len() to find the number of elements in a list

n = len(my_list)                      # find the number of elements in my_list
print(f'my_list has {n} elements')    # display the result

4.3 Use an item's index to fetch it from a list

print("first element (index 0)  = ",my_list[0])
print("second element (index 1) = ",my_list[1])
print("third element (index 2)  = ",my_list[2])

✅ Skill Check 1

Print the fourth element of the following array:

A = [2,4,6,8,10,12]

4.4 The last item in a list has index [-1]

print('The last item in my list is',my_list[-1])
print('The 2nd-to-the-last item in my list is',my_list[-2])

4.5 Indexing in Python starts at zero

This was already covered in the previous section, but it is super, super important. Some programming languages like Fortran, Matlab and R start counting at 1 because that's what people naturally do. Other languages like Python, C, Java, etc. count from 0 because it represents an offset from the first value in the array and is closer to the way computers represent arrays. If you are interested in the historical context, you can check out Mike Hoye's blog post. It takes a bit of getting used to and is why this tutorial stars all chapters and sections with 0 instead of 1.

4.6 Use slicing to fetch multiple items from a list

print("The slice new_list[1:4] =",my_list[1:4])
print("slice new_list[3:] slice =       ",my_list[3:])
print("slice new_list[3:] slice =       ",my_list[0:3])

✅ Skill Check 2

Print the first 4 elements of the following array:

A = [2,4,6,8,10,12]

4.7 A list's values can be replaced by assigning new values to them

my_list[4] = 50
print("updated list = ",my_list)
my_list[0:3] = ['a','b','c']
print("updated list = ",my_list)

4.8 Use the list method .append() to add items to the end of a list

my_list.append('goodbye')
print('updated my_list = ',my_list)
my_list.extend([80, 90, 100])
print('updated my_list = ',my_list)

✅ Skill Check 3

In the following code, we have defined three lists of prime numbers. Using the methods described in this chapter, combine these lists to a single list and then print it to the screen.

baby_primes = [2, 3, 5, 7]
teen_primes = [11, 13, 17, 19]
adult_primes = [23, 27, 29, 31, 37]

4.9 use the `del' command to delete an element or slice from a list by index

del my_list[3]
print('updated my_list = ',my_list)
del my_list[-3:]
print('updated my_list = ',my_list)

✅ Skill Check 4

The following code cell contains a list of letters and numbers. Use methods described in this chapter to remove the numbers from the list.

even_numbers = ['a', 'b', 'c', 999, 'd', 999, 'e']

4.10 Use the .remove() method to delete an element by value

my_list.remove('goodbye')
print('updated my_list = ',my_list)

4.11 Remove all elements of an array by setting it equal to the empty list []

my_list = []
print('updated my_list = ',my_list)
del my_list

4.12 Swap elements

Python provides a fancy way of swapping elements of a list (or any pair of variables).

First, let's try it with two variables x and y. We simply reverse the order of the variables across the equals sign like this:

x = 1                       # define x
y = 2                       # define y
x, y = y, x                 # swap x and y
print('x =',x,'and y =',y)  # print the result

Let's now apply this trick to lists. We'll define a list and then swap the first two elements:

A = [10, 20, 30, 40, 50]
A[0], A[1] = A[1], A[0]
print('updated A = ',A)

✅ Skill Check 5

Using only thw swap operator, write a series of commands to place the numbers in the following list in order from low to high.

my_list = [20, 50, 60, 10, 30, 40, 70]

4.13 Use .copy() to copy a list

Let's say we want to copy the following list. It is tempting to just use the assignment operator "=" as follows:

my_list = [1,2,3]              # define a list
new_list = my_list             # use "=" to set a pointer from the new list to the original
print('new_list = ',new_list)  # show that the new list contains the same elements as the original

However, something strange happens if we modify the original list:

my_list[0] = 10                # modify the original list
print('my_list = ',my_list)    # show that the orininal list was modified
print('new_list = ',new_list)  # show that the new list is also modified!!

To make a copy of a list that is not "tethered" to the original one, use the .copy() method:

my_list  = [1,2,3]             # define a list
new_list = my_list.copy()      # make an independent copy
my_list[0] = 10                # make a change to the original list
print('my_list = ',my_list)    # show that the original list was changed
print('new_list = ',new_list)  # show that the copy stays unchanged

4.14 Sort list elements

We can sort the elements of a list with the .sort() method like this:

my_list = [4, 8, 1, 9, 3, 5, 3, 1, 9, 2]

my_list.sort()
print('sorted my_list = ',my_list)

✅ Skill Check 6

The following Code Cell contains a list of particle names. Sort the list in alphabetical order and print the result.

a = ['proton','quark','gluon','electron','muon','boson']

🔆 Example - Largest three values in a list

Suppose we want to find the largest three values in a list. We can accomplish this by sorting the list and then printing the last three elements. Let's assume we don't want to change the order of the elements in the original list.

Solution

Since we don't want the mess with the ordering of our list, we do the following:

a = [5,7,9,2,1,6,4,8,10,2,7]
b = a.copy()
b.sort()
print("the largest three values are",b[-3:])

4.15 Functions and methods that work on lists

List Methods

In Python a method is a function that is defined within an object. Methods are called with the following syntax: object.method(). The previous section described how to use the sort() method on lists. Here's a list of several list methods:

Built-in functions

The following are functions buit into Python that work on lists:

🔆 Example functions and methods

my_list = [4,7,1,7,9,0,10]

print("length of my_list = ",len(my_list))
print("sum of my_list = ",sum(my_list))
print("min of my_list = ",min(my_list))
print("index of teh first 7 in my_list = ",my_list.index(7))

✅ Skill Check 7

Use the sum() function to calculate and print the average of the following list. Remember the average is the sum divided by the number of elements in the list.

my_list = [3,6,17,2,1,-8,6,1,3,9]

✅ Skill Check 8

The following code cell contains a list of values. Use the methods described in this chapter to create a new list with the minimum value and the maximum value removed. Your method should automatically find the extreme values, so that it will still work if the array elements change. Print your new list. Calculate and print the average of the new list.

my_list = [3,6,17,2,1,-8,6,1,3,9]

4.16 Character strings can be indexed and sliced like lists

element = 'carbon'
print('length of the element string = ', len(element))
print('first letter of the element (element[0]) = ', element[0])
print('first thee letters (element[:3]) = ', element[:3])

Even though strings act like lists in some ways, they are NOT lists.

element[0] = 'C'
element = element.replace('c','C')
print("updated element string =", element)

✅ Skill Check 9

The words "pancake" and "feedback" are two examples where reversing the syllables makes a meaningful word, in this case "cakepan" and "backfeed" respectively. Using slicing and concatenation, reverse the syllables of these two words

word1 = "pancake"
word2 = "feedback"

4.17 Don't confuse lists and tuples

A Python tuple is is similar to a list, but its contents cannot be changed once it is created, i.e. it is immutable. We won't discuss them much at the moment other to say they are created with parentheses instead of square brackets:

my_tuple = (1,2,3)

For now, the main take-away is: if you accidently use parentheses instead of square brackets when trying to create a list, you will actually be creating a tuple. This can lead to error messages (see below), angst and frustration if done unintentionally. Be careful with the notation!

4.18 Practice problems

4.19 Errors

The following are common errors encountered when using lists:

Mixing up [ ], ( ) and { }

Trying to define a list with parentheses ( ) or curly braces { } instead of square brackets [ ] will define the obect as a tuple or a set, respectively, rather than a list. Often, this won't throw an error immediately, since these are also valid objects. Errors will arise, however, if you try to update a tuple since tuples aren't mutable:

Index out of range error

Trying to reference a list element that is beyond the end of the list will throw an error. Remember that if a list has N elements, the last element will be[N-1] and not [N].

my_list = [1,2,3]   # list defined with 3 elements
print(my_list[3])   # valid indices run from 0 to 2, so 3 is out of bounds

Array slicing

Array slicing can often lead to errors if you try to get too fancy. Trying to assign a set of elements when the number of elements don't match. Unless you are very careful about what you are doing, this can lead to unexpected results. For example, if you want to modify the first three elements of a list, but accidently assign the three elements to the first position in the target list, you will end up with one of the list elements being a list itself. This is an allowed operation, but not what was intended:

a = [10,20,30,40,50]
a[0] = [1,2,3]
print("array a is now = ",a)

Here's the correct way:

a = [10,20,30,40,50]
a[0:3] = [1,2,3]
print("array a is now = ",a)

Key Points

This tutorial is a modified adaptation of link text "Python for Physicists"

© Software Carpentry

This tutorial is a modified adaptation of link text "Python for Physicists"

© Software Carpentry