Skip to Content

Tutorial, Part 4: Lists, for loops, built-in help.

Contact: compwiki@physics.utoronto.ca
Last updated around: 2018-07-25
To finish our tutorial, we are going to introduce lists and for loops , which are loops that iterate over elements of lists. We are also going to provide you with tips on how to further explore Python using its built-in help facilities.

1. Review

  • In the last tutorial you were introduced to while loops. A for loop is similar to a while loop but is given a list of items to process.

2. A first introduction to lists

So far we have dealt with data values and data variables "one at a time", so to speak, so that each variable can only have one value at a time; for example the assignment statement x = 2 assigns the integer 2 to the variable x , and x = x + 1 updates the variable x to have the value 3.

But suppose we want to define a variable like a force vector or a collection of birthdays that we know consists of multiple components? In that case, it makes life easier to group several numbers (or strings, or even other variables) together into a single set with multiple components.

The Python set we'll use most often is the list, which is an ordered set in which Python keeps track of the position of each element in the set. A list is a comma-separated set of numbers (or strings, or other variables, or even other lists) enclosed by square brackets. Here is an assignment statement that creates a list assigned to the variable name my_list:

python code
            my_list = [1, 2, 3, 4, 5]
print(my_list)
        

will result in

python code
            [1, 2, 3, 4, 5]
        

The variable my_list consists of five values. The first value is the integer 1, the second the integer 2, and so on. In Python, the first value of my_list is referenced using a special notation in which the index 0 corresponds to the first element, the index 1 corresponds to the second element, and so on, similar to the string example above. So my_list[0] corresponds to the value 1 and my_list[3] corresponds to the value 4. (For reasons we won't go into, several computer languages use this kind of zero-based indexing.) To see this indexing at work, look at the following example:

python code
            print(my_list[0])
        

will result in

python code
            1
        

We can alter the values of the elements of the list:

python code
            my_list[0] = 10
print(my_list)
        

will result in

python code
            [10, 2, 3, 4, 5]
        

Here we used the indexing to refer to a particular value, and then changed that value using an assignment statement. (This will not work for strings.)

The following exercise will get you familiar with some of the basic properties of lists. Try the examples and create some of your own to better understand them. Our purpose here, in the spirit of the rest of the tutorial, is not to teach you everything there is to know about lists, but to focus on what you need to know to solve problems in physics. See the discussion of lists in the Python reference(current link is for Python 2 documentation)for more information.

Activity 1: Do the following:

  • Open up a Python shell and create a new list at the prompt
python code
            my_list = [5, 4, 3, 2, 1, 0]
        

and print it by typing my_list at the next prompt.

  • Print the first and third values of my_list with my_list[0] and my_list[2].
  • The last element of my_list can be referenced by typing my_list[-1], the second last element by typing my_list[-2], and so on. At the prompt, print the last, second last, and third last elements of my_list.
  • The second, third and fourth elements can be accessed as a list by typing my_list[1:4] . Type my_list[1:4] at the prompt now. You will see that a list is printed, so my_list[1:4] is itself a list. The : (colon) notation instructs the interpreter to create a list starting with index 1 (the second element) and ending with integer up to, but not including, 4. This integer is 3, which corresponds to the fourth element. (This may be confusing, but this method of counting is consistent among common programming languages.)
  • The length of my_list can be found by typing len(my_list) . Do this now at the prompt.
  • Create a new list
python code
            my_new_list = ['apples', 'bananas', 'oranges']
        

print it, and access the second element by typing my_new_list[1].

  • Here is practice with changing the values that appear within lists. Type the following:
python code
            my_new_list[1] = 'grapes'
my_new_list
my_list[0] = -9
my_list
        
  • You can concatenate lists --- stick them together --- using the + sign, and repeat them using the * sign. To see this, type the following and look at the results:
python code
            my_list + my_list
my_list * 2
my_list * 5
my_list + my_new_list
        

The last example created a list of numbers and strings.

To finish this section, we will briefly describe the range() function, which creates a list of numbers separated by equal increments. For example, this example creates a list called my_range_list:

python code
            my_range_list = range(5)
print( my_range_list)
        

results in

python code
            [0, 1, 2, 3, 4]
        

Activity 2: Do the following:

  • Create a couple of lists using "range":
python code
            a = range(10)
print(a)
b = range(10, 2, -2)
print(b)
        

The second version of the range function call, range(10,2,-2) told python to start at 10, stop at 2, and step by -2. We will not say much more about range() here. Instead, we will now show you how to find out more about range and other Python functions, using Python's built-in help facilities.

3. Python's built-in help

Lists and the range() function are examples of powerful Python concepts that we can't cover comprehensively in this tutorial. How do you learn more about Python features? Here, we'll introduce you to the dir and help functions, which are built-in functions that document Python's features. Besides the built-in help, you should search through available help on the web.

  • The dir function provides a list of features that apply to a list or any other Python variable, set, function, etc.. (Variables, sets, functions and so on are referred to as Python objects). Here is an example that uses dir on a list you've created
python code
            a = [2, 3, 5, 10, 12]
dir(a)
        

This will produce a list in alphabetical order of "methods" --- functions ---- that apply to a. Now, you will see if you type this example that a very long list of methods is produced; there is no way you can understand what a particular method does just by the name. You can type the dir()function for any Python object, and get a list of methods that apply to it. To get help on any of the listed methods, type

help(a.method)

To use a typical method, type

a.method(<args>)

where <args> represents any arguments to the function.
To see help in action, type help(range) at the prompt.


Activity 3: Here's an example of discovering Python operations that apply to a given list within an interactive session. Look at the session excerpt below. We'll explain what's going on after we present the example, but try and understand what's happening as you read through it.

python code
            In [18]: d = ['a', 'b', 'c', 'pi', 3.14, 2**0.5, 14]
In [19]: dir(d)
 
Out[19]:
 
['__add__',
 
'__class__',
 
'__contains__',
 
'__delattr__',
 
...
 
'append',
 
...
 
'insert',
 
'pop',
 
'remove',
 
'reverse',
 
'sort']
In [20]: help(d.append)
 
Help on built-in function append:
append(...) method of builtins.list instance
 
L.append(object) -> None -- append object to end

In [21]: d.append(15)
In [22]: d

Out[22]: ['a', 'b', 'c', 'pi', 3.14, 1.4142135623730951, 14, 15]
In [23]: help(d.reverse)

Help on built-in function reverse:
reverse(...) method of builtins.list instance

L.reverse() -- reverse *IN PLACE*
 
In [24]: d.reverse()
In [25]: d
 
Out[25]: [15, 14, 1.4142135623730951, 3.14, 'pi', 'c', 'b', 'a']
        

Here's what happens:

  1. We start by creating a list of strings and numbers d .
  2. We then ask what kind of operations can be applied to d ( dir(d) ). The result is a list of methods; for now we'll ignore the ones that are marked by double underscores like __add__ ; and use the standard methods such as pop .
  3. We see that there is a function ("method") called append , and ask for help on this method ( help(d.append) ).
  4. We then append the number 15 to d ( d.append(15) ), and print out the new d , which has 15 tagged on the end.
  5. We then ask for help on the reverse function ( help(d.reverse) ).
  6. We then reverse d using d.reverse() , and print out the new d . Notice that order of the elements in d has been reversed.

4. The for loop

In Part 3, we introduced the while loop that continues executing as long as a condition is True. The for loop is another kind of loop that iterates over values in a list. This is best explained by example:

python code
            #Create a list from 0 to 9
a = range(10)
print("a is ", a)
#Iterate over the values in "a"
for val in a:
    #As for previous statements (if, while, etc.) the blocks are denoted by indentation.
    print ("The current value is ", val)
    if val>5:
        print ("This value is greater than 5")
        print ("The square of this value is", val**2)
print ("Done.")
        
python code
            import numpy as np
a = np.array([0,10,20,30,40])
a
a[:]
a[1:3]
a[1] = 15
a
b = np.arange(-5, 5, 0.5)
b
b ** 2
1/b
1/b[10]
        

7. Recap

This concludes the Part 4 of the tutorial. In summary:

  1. We have learned about lists like a=[1,2,3,4] and what kind of operations can be done on them.
  2. We have learned how to explore possible actions on an object with dir(my_object) and help(my_object.method)
  3. We have learned about for loops, which iterate over a list.

We have also discussed a few examples of problem solving. The strategy we use is to

  1. Come up with some clearly written formulas that you want to code up on a computer.
  2. Include a lot of comments in the code.
  3. Include helpful hints on input (like descriptive prompts) and on output.

We hope that this tutorial has helped start you on the path to doing physics with computers. Please speak to your instructor if you have any suggestions for how to improve this tutorial.

Part_4_Questions.pdf

Part_4_Solutions.pdf


This concludes part 4 of the tutorial.