Module 3 - Section 2 - Lists

Site: ΕΛ/ΛΑΚ Moodle
Course: Python Lab
Book: Module 3 - Section 2 - Lists
Printed by: Guest user
Date: Wednesday, 4 December 2024, 10:27 AM

Description

After the completion of this module the students will be able to:

  • identify the various data types
  • recognize lists
  • create lists
  • use the list methods
  • use the random function

3.2.1 - Data types

So far we have seen three types of data :

and we learned that we can display the type of data with type function.

You can try the following to remember types :

>>> type(3)

>>> type(3.14)

>>> type("Hello")

We have also spoken about statements and we know that some are True and others are False. Try the following code :

>>> type(True)  # without quotes

>>> type(False) # without quotes

This is another type of data called Boolean and could be one of this words.

List is another type of data. We have created lists using the command range. Then we created lists of numbers.

>>>  list(range(1,11))

But a list can contain multiple data. Lets try an example with numbers:

>>> my_list = [1,33,18]

>>> print (my_list) # this is a list of numbers

3.2.2 - Lists

So what should i do if i want to create a shopping list? Copy the following command and test it.

>>> my_shopping_list = ["apples","bananas","carrots"] 

>>> print(my_shopping_list)

The items in the list are numbered starting from 0 (as we mentioned in programming we usually start from 0).

So  the 0 item in my_shopping_list is "apples"

      the 1 item is "bananas"

and the 2 item is "carrots"

Try the following :

>>> print(my_shopping_list[0]) # in print we use parenthesis () and in lists square brackets [])

>>> print(my_shopping_list[1])

>>> print(my_shopping_list[2])

>>> print(my_shopping_list[3])

In the last example there is an error :

Traceback (most recent call last):

  File "<pyshell>", line 1, in <module>

IndexError: list index out of range

because myshoppinglist does not have an item indexed 3

we can change an item in list :

>>> my_shopping_list[0] = "apricots"

>>> print(my_shopping_list)

And we can iterate (loop) through a list. Copy the following code to Thonny and save it as list_friends.py inside your working folder:

my_friends = ["Jim", "John", "Jack", "Jane"] for item in my_friends: print (item)

We can view the number of items in a list with command len.

>>> len(my_friends)

and we can add items to a list :

>>> my_friends.append("Joe")

>>> print(my_friends)

Our list has 5 items now. Check its length.

3.2.3 - List methods

Lists are mutable objects. This means that we can change a list, add or remove items find the minimun and the maximun or even add one list items to another list.

You can learn more about lists here https://docs.python.org/3/tutorial/introduction.html#lists

and you can find some of the list methods here https://docs.python.org/3/tutorial/datastructures.html#more-on-lists 

We will start creating a list an empty list :

>>> new_list=[]

After that we can add items using the append command :

>>> new_list.append(13)

And we can add a range of numbers :

>>> for i in range(1,21):
        new_list.append(i)

We can view the list and its contents in the variable view of Thonny. We can also view the list with the command :

>>> new_list

If we want to count the instances of an item inside the list we can use the method count :

>>> new_list.count(13)

If we want to remove an item we can use the remove method to remove the first instance of an item :

>>> new_list.remove(10)

>>> new_list.remove(13) # removes only the first 13

We can sort the list in normal (ascending) order :

>>> new_list.sort()

and we can sort it in reverse order (descending) :

>>> new_list.reverse()

We can also find the position of an item :

>>> new_list.index(18)

Finally we can find the maximun and minimum of a list :

>>> max(new_list)

>>> min(new_list)

and we can add the items of a list :

>>> sum(new_list)

and many more that you can search in the links above.

3.2.4 - Summing a list

So, how can we add all the items in a list using the sum command? This is very easy, but lets think how we can we the same with our own code.

Copy the following code to Thonny and save it as sumlist:


Take a closer look to the command range(len(my_list)). What do you think it does?

We can change the code to the following. Copy and paste it again to Thonny and save it as sumlist2 :


Try to find the differences of the two previous codes.

As an exercise write a code to create a list of all integer numbers from 11 to 91 and then calculate the sum of this list. You should find 4131

Steps

  1. create an empty list with any name (ex. new_list)
  2. with a for loop append numbers from 11 to 91 to the list
  3. create a variable total to sum the numbers and initiate it to 0
  4. with a new for loop add all items of the list to total variable

The solution can be found here.

3.2.5 - Random

Random is a function that creates random numbers. It is not in the core of Python but in a library (the random library). In order to use it first we have to import the library. Copy the following code to Thonny and save it as Randomize.

import random print (random.randrange(1,50))


If we wanted to randomly select a number between 50 and 80 then the code should be :

import random print(random.randrange(50,81))


You can explore random function and how to use it in several cases here

To combine lists with random we will create a list of 20 random numbers from 1 to 80 like in the kino game.

Copy the following code to Thonny's editor and save it as kino.py.


Are the numbers in the list unique?

3.2.6 - Random extended

Also there is a way to pick a random item out of a list. Copy the following code to Thonny and save it as rock_paper_scissors.py :


All of the prior code generates integer numbers. If a floating point number is desired, a programmer should use the random method.

The code below generates a random number from 0 to 1

import random my_number = random.random()


and the following code creates a random number between 10 and 45

import random my_number = random.random() * 35 + 10


Can you create a code that generates a random number between 27 and 42?