$$ \newcommand{\tp}{\thinspace .} $$

Loops and lists

Hans Petter Langtangen [1, 2]

[1] Center for Biomedical Computing, Simula Research Laboratory
[2] Department of Informatics, University of Oslo

Jun 14, 2016


Table of contents

While loops
      A naive solution
      While loops
      Boolean expressions
      Loop implementation of a sum
Lists
      Basic list operations
      For loops
Alternative implementations with lists and loops
      While loop implementation of a for loop
      The range construction
      For loops with list indices
      Changing list elements
      List comprehension
      Traversing multiple lists simultaneously
Nested lists
      A table as a list of rows or columns
      Printing objects
      Extracting sublists
      Traversing nested lists
Tuples
Summary
      Chapter topics
      Example: Analyzing list data
      How to find more Python information
Exercises
      Exercise 1: Make a Fahrenheit-Celsius conversion table
      Exercise 2: Generate an approximate Fahrenheit-Celsius conversion table
      Exercise 3: Work with a list
      Exercise 4: Generate odd numbers
      Exercise 5: Compute the sum of the first \( n \) integers
      Exercise 6: Compute energy levels in an atom
      Exercise 7: Generate equally spaced coordinates
      Exercise 8: Make a table of values from a formula
      Exercise 9: Store values from a formula in lists
      Exercise 10: Simulate operations on lists by hand
      Exercise 11: Compute a mathematical sum
      Exercise 12: Replace a while loop by a for loop
      Exercise 13: Simulate a program by hand
      Exercise 14: Explore Python documentation
      Exercise 15: Index a nested list
      Exercise 16: Store data in lists
      Exercise 17: Store data in a nested list
      Exercise 18: Values of boolean expressions
      Exercise 19: Explore round-off errors from a large number of inverse operations
      Exercise 20: Explore what zero can be on a computer
      Exercise 21: Compare two real numbers with a tolerance
      Exercise 22: Interpret a code
      Exercise 23: Explore problems with inaccurate indentation
      Exercise 24: Explore punctuation in Python programs
      Exercise 25: Investigate a for loop over a changing list
References

This document explains how repetitive tasks in a program can be automated by loops. We also introduce list objects for storing and processing collections of data with a specific order. Loops and lists, together with functions and if tests, constitute the very fundamentals of computer programming. The programs associated with the document are found in the folder src/looplist.

This chapter is taken from the book A Primer on Scientific Programming with Python by H. P. Langtangen, 5th edition, Springer, 2016.