---
# System prepended metadata

title: 'Lists: Iterating over Lists'

---

# Lists: Iterating over Lists


([home](https://github.com/alexhkurz/introduction-to-programming/blob/master/README.md) ... [previous](https://hackmd.io/@alexhkurz/r1erdGSlP) ... [next](https://hackmd.io/@alexhkurz/By6YoM8Gw) ... )

In the previous lecture we looked the complexity of a simple sorting algorithm. But we did not implement this algorithm in an actual programming language. We only analysed the time complexity of any such implementation.

To implement sorting in a programming language we need a data structure that collects elements in an ordered fashion. For example, we may collect numbers in a list

    [1,2,3,4]
    
We also have a list with no elements, the emtpy list

    []
    
Elements of a list can be accessed by their position (or index) in the list. Such lists are also known as **arrays** or **vectors** The first position has index `0`, the second has index `1`, and so on. For example, we can have the following dialogue with Python.

	>>> l = [4,3,2,1]
	>>> l
	[4, 3, 2, 1]
	>>> l[0]
	4
	>>> l[1]
	3
	>>> l[4]
	Traceback (most recent call last):
	  File "<stdin>", line 1, in <module>
	IndexError: list index out of range    

We can use this to print all the elements of a list.
    
	>>> for i in range (0,4):
	...     print(l[i])
	... 
	4
	3
	2
	1

In many imperative programming languages (such as C), this is essentially how one would iterate through an array. Python instead offers a more elegant way:

	>>> for x in l:
	...     print(x)
	... 
	4
	3
	2
	1

Let us practice this idea of using a `for`-loop to iterate through a list with the following exercise.

**Activity:** Write a Python program that computes the length of a list. Complete the program below.

    my_list = [4,1,-1,10]
    
    def length(list):
        <your code here>
        
    print(length(my_list))
    
- The function length should return the length of `list`. Remember the session on [`for`-loops](https://hackmd.io/@alexhkurz/H1o4Mcr6L). Think and try for yourself. Only then, if you need a hint, read the footnote.[^Hints]
- Test your program with different lists. Make sure that you include the empty list in the tests.

**Homework/Activity:** Assume that we know that all the elements of the list are integers. Write Python programs that compute

- the sum of the elements of the list;
- the product of the elements of the list; 
- the average of the elements of the list.



[^Hints]: Use an auxiliary variable to successively compute the length of `list`, similarly to how we used `sum` in the first activity of the session on [`for`-loops](https://hackmd.io/@alexhkurz/H1o4Mcr6L). Recall how the [`return`-statement](https://hackmd.io/@alexhkurz/HJHS4NUAI) works. 

