LearnWave
Learn it. Master it.

Lists

Lists and functions

Write a function that works on a list.

When a list is passed to a function, the function receives a reference to the same list, not a copy. So if the function changes the elements (for example, list2[i] += 5 in Program 9-1), the caller sees the changes.

But if the function assigns a whole new list to its parameter (list2 = [15, 25, 35] in Program 9-2), the parameter now refers to a new, local list. The caller's list is unchanged.

The book shows several list programs:

  • Program 9-3 is a menu-driven program: inside a while loop, it offers choices to append, insert or extend elements, modify one, delete by position or by value, sort the list, or display it.
  • Program 9-4 reads n marks into a list using append(), and passes the list to a function computeAverage() that returns their average.
  • Program 9-5, linearSearch(num, list1), checks each element in turn. If it finds num, it returns its index; if it reaches the end without finding it, it returns None.

Remember: change the elements, and the caller sees it; reassign the whole list, and the caller does not.

Change elements: the caller sees it. Reassign: it doesn't.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.