Chapter 9 : Lists in Python


 Project management 

This chapter is designed to familiarize the learner with the operation and processing of lists in Python. Lists are a particularly powerful tool that must be mastered.

Four solved exercises are presented. Following these exercises, a summary of list theory is provided to help solve the exercises.

 Objective 

Practice using the power of lists to write programs in Python.

 Lists in Python, exercises 

The exercises below are taken/inspired from the excellent book "L'informatique simplement" by Juraj Hromkovič and Tobias Kohn, published by LEP (Switzerland). This book is highly recommended for Python beginners.

Exercise 1: The program asks the user how many people will be attending the meeting. Next, the program asks for the ages of all participants. Finally, the program displays the ages of all participants in ascending order.

See a solution

Note: this solution does not take into account the fact that the user can enter any characters on the keyboard, so this program is not robust.

age_participants = [ ]
number = int(input("What is the number of participants? "))
for i in range (number):
     age = int(input("What is the age of this participant? "))
     age_participants.append(age)
age_participants.sort()
print ("Here are the participants' ages in ascending order: ",age_participants)

Hide this solution

Exercise 2: The program starts with a list of 10 numbers from 1 to 10. The program then asks what number multiples of this list should be replaced by a star (*). Finally, the program displays the list of numbers and stars.

See two solutions

Note: these solutions don't take into account the fact that the user can enter any characters on the keyboard, so these programs are not robust.

sequence_numbers = [1,2,3,4,5,6,7,8,9,10]
to_delete = int(input("From which number below 11 should I remove the multiples? "))
for number in sequence_numbers :
     if int (number / to_delete) == (number / to_delete):
          print ("* ,", end=" ")
     else:
          print (number,",", end=" ")

Another solution is to use the modulo function, represented by the abbreviation %, which gives the remainder of the integer division. The program would look like this.

sequence_numbers = [1,2,3,4,5,6,7,8,9,10]
to_delete = int(input("Of which number less than 11 should I remove the multiples? "))
for number in sequence_numbers :
     if number % to_delete == 0:
          print ("* ,", end=" ")
     else:
          print (number,",", end=" ")

Hide these solutions

Exercise 3: The program starts with a mixed list of even and odd numbers. At the end, the program must display the list of even numbers and the list of odd numbers, the two lists being sorted in descending number order.

See a solution

Note: this solution doesn't perform any keyboard reading, so the question of robustness doesn't arise.

list_of_numbers = [12,36,5,17,124,54,51,112]
even = [ ]
odd = [ ]
for number in list_of_numbers :
     if number % 2 == 0 :
          even.append(number)
     else :
          odd.append(number)
even.sort()
even.reverse()
odd.sort()
odd.reverse()
print ("The even numbers in the list, in descending order, are:", even)
print ("The odd numbers in the list, in descending order, are:", odd)

Hide this solution

Exercise 4: The program starts with a list of numbers that you choose at random. The program then displays my average of the numbers in this list.

See a solution

Note: this solution doesn't read from the keyboard, so the question of robustness doesn't arise.

list = [0,1,2,3,4,5,6]
sum = 0
for number in list :
     sum += number
average = sum / len(liste)
print ("The average of the numbers in the list is",average)

Hide this solution



 Lists in Python, theory 

Lists are an extremely powerful and practical tool in Python, and it's in your interest to master them as much as possible to make your life easier.

1. Declaring an empty list

my_list = [ ] # These are two successive square brackets, opening and closing.

2. Initialize a list, i.e. declare it non-empty

my_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
my_list = [1, 3, 5, 7, 11]
my_list = list (range (10)) # will contain the sequence of 10 numbers from 0 to 9 inclusive
my_list = list (range (5, 15)) # will contain the sequence starting with 5 to and ending with 14

3. Referencing list items

Each element of the list has a position index, the first element having index 0.
my_list1 = [1, 3, 5, 7, 11]
print (my_list1 [1]) # will display the number 3.
If the index is outside the list, the message "list index out of range" appears.

4. Browse a list

for value in my_list1 :
    print (value) # will print all the contents of the list, try it.

5. Check if an element is part of a list

The expression 10 in my_list1 will give a True or False result, in this case false.

6. Know the length of a list

print (len (my_list1)) # will display 5, the number of elements in the list referenced from 0 to 4

7. Add item to end of list

my_list1.append (13) # adds element 13 to the end of the list, which will contain 6 elements.

8. Inserting an element in a list

my_list.insert (position, element) # inserts the element at the position in the list.
Example: list_days = ['monday', 'wednesday']
list_days.insert (1, 'thursday']
print (list_days) # will print ['monday', 'thursday', 'wednesday']

9. Modifying a list item

day_list [1] = 'tuesday'
print (list_days) # will print ['monday', 'tuesday', 'wednesday']

10. Combining lists

There is a way to complete an original list with the contents of another list. Example:
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
week_end = ['Saturday', 'Sunday']
week.extend (week_end)
print (week) # will display ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

11. Deleting a list item

Either based on the element itself, or on its index.
letters = ['a', 'b', 'c', 'd']
letters.remove ('c') # delete based on the element itselfsaid
print (letters) # will display ['a', 'b', 'd']
del letters[1] # delete based on position
print (letters) # will display ['a', 'd']
letters.pop (0) will have the same effect as del. In this case, the first element of the list will be deleted, since the index here is 0.

12. Deleting several identical items from a list

numbers = [0, 1, 2, 0, 3, 0, 4, 0, 5]
while 0 in numbers :
    numbers.remove (0)
print (numbers) # will display [1, 2, 3, 4, 5].

13. Empty a list

numbers.clear ()
print (numbers) # will display [$nbsp;]

14. Count the number of occurrences of an element in a list

numbers = [0, 1, 2, 0, 3, 0, 4, 0, 5]
print (numbers.count (0)) # will display 4

15. Find the index of a list element

numbers = [0, 1, 2, 0, 3, 0, 4, 0, 5]
print (numbers.index (3)) # will display position 4 as counting starts at 0.
If the element is not in the list, an error will occur. A robust program will first check if the element is in the list before requesting its index (using if: and else:).

16. Sorting a list

numbers = [0, 1, 2, 0, 3, 0, 4, 0, 5]
numbers.sort()
print (numbers) # will display [0, 0, 0, 0, 1, 2, 3, 4, 5].

17. Inverting a list

numbers.reverse()
print (numbers) # will display [5, 4, 3, 2, 1, 0, 0, 0, 0].

18. Copy a list

list_one = ['adieu', 'veaux', 'vaches', 'cochons', 'couvées']
list_two = list_one.copy() # creates list_two containing a copy of list_one.

19. What is a "tuple"?

A tuple is a list that cannot be modified later. See details on the Internet.

Good work, be brave... :O)

Return