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
Goals
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.
my_list = [10, 20, 30, "hello", True, 60]
print('my_list contains these items: ',my_list)
len() to find the number of elements in a listn = len(my_list) # find the number of elements in my_list
print(f'my_list has {n} elements') # display the result
print("first element (index 0) = ",my_list[0])
print("second element (index 1) = ",my_list[1])
print("third element (index 2) = ",my_list[2])
Print the fourth element of the following array:
A = [2,4,6,8,10,12]
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])
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.
[start:stop] notation, where start is replaces with the index of hte first item we want and stop is the index just after the last item we want.stop and start is the length of the list.print("The slice new_list[1:4] =",my_list[1:4])
stop will extend the slice from start to the end of the list:print("slice new_list[3:] slice = ",my_list[3:])
start will extend the slice from 0 up to stop:print("slice new_list[3:] slice = ",my_list[0:3])
Print the first 4 elements of the following array:
A = [2,4,6,8,10,12]
my_list[4] = 50
print("updated list = ",my_list)
my_list with the letters a, b, c.my_list[0:3] = ['a','b','c']
print("updated list = ",my_list)
.append() method. We'll add an element "goodbye" to the end of our list:my_list.append('goodbye')
print('updated my_list = ',my_list)
.extend() method. We'll add a list `[80, 90, 100]' to the end of our list:my_list.extend([80, 90, 100])
print('updated my_list = ',my_list)
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]
del my_list[3]
print('updated my_list = ',my_list)
del my_list[-3:]
print('updated my_list = ',my_list)
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']
.remove() method to delete an element by value.remove() method to provide the contents of the element. The .remove() command will delete the first occurance of the element from the list. If the value appears in multiple locations in the list, the others will remainmy_list.remove('goodbye')
print('updated my_list = ',my_list)
[]my_list = []
print('updated my_list = ',my_list)
del command. After running the following command, my_list will no longer show up in the Variable Inspector.del my_list
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)
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]
.copy() to copy a listLet'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
.copy() method the two lists are independent and modifying one won't affect the other.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)
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']
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:
.copy()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:])
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:
x to the end of a listx at index position ixxBuilt-in functions
The following are functions buit into Python that work on lists:
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))
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]
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]
len() counts the unber of characters in a string, just like it returns the number of elements in a listelement = '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'
.replace() method for strings. Because, you cannot edit strings, you have to save the modified version as a new string. And, yes, it is ok to save it with the same name. This bascially overwrites the old string with the new one. You can do much more as well, but that is beyond the scope of the current discussion.element = element.replace('c','C')
print("updated element string =", element)
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"
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!
The following are common errors encountered when using lists:
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:
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 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)
[item1, item2, item3...]len() function returns the number of elements in a listmy_list[0]my_list[-1]my_list[start:end].append() to add items to the end of a listdel command to delete items from a list by index.remove() method to delete items by valuea[1],a[2] = a[2],a[1].copy() method() you will be creating a tuple, which has very different properties.This tutorial is a modified adaptation of link text "Python for Physicists"
This tutorial is a modified adaptation of link text "Python for Physicists"