LearnWave
Learn it. Master it.

Working with Lists and Dictionaries

List manipulation programs

Build a list from input and search it.

The book's programs put list methods to work.

Program 4-1: a menu of list operations. It starts with myList = [22, 4, 16, 38, 13], shows a menu (append, insert, extend with a list, modify, delete by position, delete by value, sort ascending, sort descending, display), reads the user's choice with int(input(...)), and carries out that operation using if..elif..else.

  • It reads elements with eval(input(...)), so the user can type a number or even a whole list, which eval() turns into a Python value.
  • Before modifying or deleting by position, it checks that the position is less than len(myList); otherwise it reports that the position is beyond the list.
  • Before deleting by value, it checks the value is in the list, so remove() never raises an error.
  • It sorts with sort() and sort(reverse = True), and deletes by position with pop(i).

Program 4-2: average marks of n students. It creates an empty list (list1 = []), reads n, then in a loop reads each student's marks and appends them. It then adds up the marks in a total and divides by n to get the average.

Program 4-3: searching a list. It reads numbers into an empty list, then the number to search for. It sets position = -1 (meaning 'not found yet'), loops through every index, and when an element equals the number, records its position counting from 1 for the user (index + 1). At the end, if position is still -1 it says the number is not present; otherwise it prints where it was found.

  • The pattern in all three: start empty, append in a loop, then process.

Example (new): to collect daily temperatures for a week, start with temps = [], loop 7 times appending float(input(...)), then print max(temps), min(temps) and sum(temps) / 7 for the hottest, coolest and average day.

Start empty, append in a loop, then process.

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.