In this ICS3U Grade 11 Computer Science lesson you will be learning to:
Computer programs are very good at storing and manipulating a lot of data quickly and efficiently. To do this they rely on something called a data structure. It gives the programmer a nice way to organize and access large amounts of data There are different kinds of data structures, and in this lesson we will be looking at list and String data structures.
Lists store data in an organized way. They are sometimes called arrays. They are effectively just a numbered collection of variables that were designed to allow efficient access and manipulation.
You must give a list a name (just like a variable) but you use square brackets [] to define quantities in a list. You can store any type of data that you want inside the list. The values in the list don’t have to be the same type.
people = ["Teacher", "Student", "Parent", "Principal", "Caretaker"]
numbers = [8, 9, 4, 3, -2, 14, 5, -6]
mixed = ["hi", 5, 3.25, "Bye", "Paul", 4]
Printing the values in a list works exactly the same way as printing the value of a variable. (Although you will probably notice its not the most user friendly / “pretty” way to display the data on the screen.
Type the following code into the Python Editor and run the program
people = ["Teacher", "Student", "Parent", "Principal", "Caretaker"]
numbers = [8, 9, 4, 3, -2, 14, 5, -6]
mixed = ["hi", 5, 3.25, "Bye", "Paul", 4]
print(people)
print("Here is my list", numbers)
print("A mixed list: ", mixed, "is cool")
Each data value in a list is called an item. You can think of each item having its own variable name. That variable name consists of the name of the list along with the location of the item within the list, which we call an index #. Lists are ordered starting at index 0
Take the example above in the people list
people = ["Teacher", "Student", "Parent", "Principal", "Caretaker"]
mixed = ["hi", 5, 3.25, "Bye", "Paul", 4]
#Prints the first value in the list
print(mixed[0])
#Adds up the second and third value
total = mixed[1] + mixed[2]
Be very careful when accessing values in a list. It is quite common to get a “list index out of range” error when running the program. It typically happens with the last index and programmers forget that the last value of the index is one less than the number of values in the list
Type the following code into the Python Editor and run the program
numbers = [8, 9, 4, 3, -2, 14, 5, -6]
print(numbers[8])
people = ["Teacher", "Student", "Parent", "Principal", "Caretaker"]
numbers = [8, 9, 4, 3, -2, 14, 5, -6]
numPeople = len(people)
numNumbers = len(numbers)
Finding a Random Value in a list
There are a few different ways to accomplish this task.
Type the following code into the Python Editor and run the program
import random
#The List
numbers = [8, 9, 4, 3, -2, 14, 5, -6]
#Generating a random index
randomIndex = random.randint(0,len(numbers)-1)
#Getting the random item using that random index
firstNum = numbers[randomIndex]
print("A random item is: ", firstNum)
#Getting the random item using the choice function from the random library
secondNum = random.choice(numbers)
print("A random item is: ", secondNum)
The fact that lists keep an ordered version of its variables is extremely useful.
for i in range(0,len(listName))
Type the following code into the Python Editor and run the program to see all of the items printed on a separate line
myNumbers = [4, 8, 15]
for i in range(0,len(myNumbers)):
print(myNumbers[i])
The value of i starts at 0
The value of i then increases to 1
The value of i then increases to 2
len(myNumbers) is 3, but the for loop is exclusive, so once its counter gets to 2 it will stop after finishing that iteration
You should have seen all the values in the list printed each on their own separate line.
myNumbers = [4, 8, 15]
for i in range(0,len(myNumbers)):
print(myNumbers[i], end = " ")
myNumbers = [4, 8, 15]
for i in range(0,len(myNumbers)):
if i < len(myNumbers)-1:
print(myNumbers[i], end = ",")
else:
print(myNumbers[i])
You might find it useful at some point to be able to add up all the values stored in a list.
There are several ways to do this
myNumbers = [4,8, 15, 36, 17, 46]
#Method #1 -> Using a loop
total = 0
for i in range(0, len(myNumbers)):
total = total + myNumbers[i]
print("The sum is:",total)
#Method #2 -> Using the sum function
total = sum(myNumbers)
print("The sum is:",total)
Another common task with a list is to be able to find the maximum or minimum value inside the list
Again, there are several ways to accomplish this task.
Type the following code into the Python Editor
myNumbers = [4, 8, 3, 36, 17, 3, 32, 14, 2, 18]
#Method #1 -> Using a loop
theMax = myNumbers[0]
for i in range(1,len(myNumbers)):
if myNumbers[i] > theMax:
theMax = myNumbers[i]
print("Max Value in the list is: ", theMax)
#Method #2 -> Using the max function
theMax = max(myNumbers)
print("Max Value in the list is: ", theMax)
The code starts with setting theMax to 4.
When the loop starts i represents the location in the list of the number being compared to the max (myNumbers[i])
This process continues to the end of the list where it will store the maximum value in the variable theMax
myNumbers = [4, 8, 15, 36, 17, 3, 36, 14, 2, 18]
#Method #1 -> Using a loop
theMin = myNumbers[0]
for i in range(1,len(myNumbers)):
if myNumbers[i] < theMin:
theMin = myNumbers[i]
print("Max Value in the list is: ", theMin)
#Method #2 -> Using the max function
theMin = min(myNumbers)
print("Max Value in the list is: ", theMin)
Any value in a list can be modified, or you can delete items from the list, or even add values to the list after it has been created.
Changing Existing Values
You can change the value of an item in the list by using the item variable and an assignment statement
Type the following code into the Python Editor and observe the changes to the list
numbers = [8,5,4,-3,1,7,-2,0,4]
print("Original List:\t",numbers)
numbers[1] = 2
numbers[4] = 9
print("New List:\t", numbers)
Deleting Existing Values
There are several different functions that can be used to remove items from a list
Type the following pieces of code into the editor and observe the changes in the list and how each function behaves
numbers = [10, 12, 17, 32, 45, 52, 29, 3, 1, 0, 18]
print("Original List: ", numbers)
#Delete the value of the first index in the list
del numbers[0]
#Delete the value at index 3 in the list
del numbers[3]
print("New List: ", numbers)
numbers = [10, 12, 17, 32, 45, 52, 29, 3, 1, 0, 18]
print("Original List: ", numbers)
#Delete the item at index 3 and get its value
atThree = numbers.pop(3)
print("New List: ", numbers)
print("What was removed: ", atThree)
numbers = [10, 12, 17, 32, 45, 52, 29, 3, 1, 0, 18]
print("Original List: ", numbers)
#Delete the values from index 1 to 3 (the 4 is exclusive, so only to 3)
del numbers[1:4]
print("New List: ", numbers)
numbers = [10, 12, 17, 32, 45, 52, 29, 3, 1, 0, 18]
print("Original List: ", numbers)
#Delete an entire list
numbers.clear()
print("New List: ", numbers)
letters = ["A", "B", "C", "D", "E", "F"]
print("Original List: ", letters)
#Remove B from the list
letters.remove("B")
print("New List: ", letters)
letters = ["A", "B", "C", "D", "E", "F", "C"]
print("Original List: ", letters)
#Remove first occurance of C from the list (Doesn't remove all)
letters.remove("C")
print("New List: ", letters)
Adding Values into the list
You can add items to the end of the list or insert them at an index of choosing
Type the following code into the Python Editor and observe the changes to the list and how the functions work
people = ["Paul", "Liane", "Kristyn"]
print("Original List: ", people)
#Adding values to the end of a list
people.append("Pierson")
people.append("Mark")
print("New List: ", people)
people = ["Paul", "Liane", "Kristyn"]
print("Original List: ", people)
#Adds an item at a specified location
people.insert(1,"Pierson")
print("New List: ", people)
Adding values to an empty List
Often times you will have the user enter a lot of information all at once from the keyboard or maybe generate a bunch of random numbers. Storing those values in a list will let your program manipulate them later on.
Type the following code and observe how items are added to the list in the loop
#Start with a blank list
myList = []
#Add a value to the list each time through the loop
for i in range(0,10):
value = input("Enter list value: ")
myList.append(value)
#Display the final list
print(myList)
Watch a video of your teacher summarizing the learning content for this section
If you are looking for some other examples of using Lists for common programming scenarios, check out this external resource. There are solutions to the questions as well as some explanations.
Although Strings are a regular data type, You can consider a string as a list of its individual characters. So each character in the String is considered as an item of the list. Many of the things we can do with arrays, we can do with Strings. There are also some other string functions that you might find useful. The biggest difference between them is that Strings are “immutable”. You can’t modify the letters in the String as easily as you can if the they were stored as a list.
If you want to access the individual characters in a String
word = "snake"
#Stores the letter s in the variable
firstLetter = word[0]
The length of a String is found the same way as the length of a list.
word = "snake"
numLetters = len(word)
Any two Strings can be joined together to form a longer string using the + operator. This is called concatenation of Strings
word1 = "Hello"
word2 = "World"
#HelloWorld stored in newString
newString = word1 + word2
It is a useful skill to be able to build up a new String using individual characters from something else
Type the following code into the Python editor and observe what happens
newWord = ""
for i in range(0,5):
letter = input("Enter a single Letter: ")
newWord = newWord + letter
print("You formed: ", newWord)
Let’s say the user entered the letters
The first time through the loop, newWord is empty and letter = “h”, so newWord becomes “h”
The next time through the loop, newWord is “h” and letter = “e”, so newWord becomes “he”
The next time through the loop, newWord is “he” and letter = “l”, so newWord becomes “hel”
The next time through the loop, newWord is “hel” and letter = “l”, so newWord becomes “hell”
The final time through the loop, newWord is “hell” and letter = “o”, so newWord becomes “hello”
#A list of characters
myList = ["M","y"," ","m","a","r","k"," ","i","s"," ","9","7"]
#Blank String to start
newWord = ""
#Loop for as many characters as in the list
for i in range(0,len(myList)):
#Add a single character to the existing string
newWord = newWord + myList[i]
#Print out the new Word
print("You formed: ", newWord)
If you have a String with multiple words all separated by spaces, then you can access each individual word using the split function. The split function will separate the string based on wherever whitespace occurs. It stores that information in a list.
You could even force it to split a String that is separated by any character, such as a comma. That character is often called a delimiter in programming
Type the following code into the Python editor and observe what gets stored in each list after the split is executed
myString = "Luke I am your father"
#Get the list
words = myString.split()
print(words)
#Get the individual words
for i in range(0, len(words)):
print(words[i])
myString = "1,2,3,4,5,6,7,8"
#Get the list using a delimiter
words = myString.split(",")
print(words)
#Get the individual numbers
for i in range(0, len(words)):
print(words[i])
You can get a portion of any String (often called a substring) between two index values by splicing the String just like you would splice a list. Remember the last entry in the index is exclusive
s = "It's not my fault"
sub1 = s[2:7]
sub2 = s[:10]
sub3 = s[3:]
Strings can be converted to only upper and lower case letters.
s = "It Does Not Do Well To Dwell On Dreams And Forget To Live."
#Make a new string with all upper or lower case original not changed
newLower = s.lower()
newUpper = s.upper()
#Change the original string to upper or lower case
s = s.lower()
s = s.upper()
This might be useful in an if statement with user input, because you wouldn’t have to worry if the user typed a word with a mix of upper or lower case
choice = input("Please Enter yes to do something: ")
#Won't matter if yes or YES or any combination was entered)
if(choice.upper() == "YES"):
#Do Something
Python has a function for strings that will count how many times a particular character occurs in a String. It is case sensitive. If necessary you might need to convert to upper or lower case.
myString = "Daddy, can I have a snack in the living room"
#Make lower case
myString = myString.lower()
#Counting a's
numA = myString.count("a")
#Counting i's
numi = myString.count("i")
Watch a video of your teacher summarizing the learning content for this section
Try to code the following ICS3U questions using an IDE of your choice (Spyder, IDLE, Pycharm, etc). You will save those files on your computer for future reference.
Each question has:
Try your best to solve the problems yourself without looking at the solutions.
Make sure you test your programs with multiple different inputs to ensure it is functioning properly.
Name Your File: “ICS3UcountTargetList.py”
Write a program that displays a random list of 75 numbers between 15 and 50 to the user. Once that list is displayed, ask them for a target to search for. Display how many of the target values are in the list.
import random
#Generate the random values and store in a list
values = []
for i in range(0,75):
num = random.randint(15,50)
values.append(num)
print(values)
#Get the target number
target = int(input("Count What? "))
#Search the list and increase the count
count = 0
for i in range (0,len(values)):
if values[i] == target:
count = count + 1
print("There were ",count,target,"'s")
Name Your File: “ICS3UcountCharacters.py”
Write a program that gets a sentence from the user and counts all the letters in it. Store the answers in the list. Index 0 being the number of a’s and index 25 being the number of z’s.
#Convert message to lower case to count
message = input("Enter your message: ").lower()
#All the possible letters
target = "abcdefghijklmnopqrstuvwxyz"
#list to store the counts
count = []
#Go through each target letter and count
for letter in range(0,len(target)):
#The letter to count
lookingFor = target[letter]
#The number of them found
numFound = message.count(lookingFor)
#Add to the list
count.append(numFound)
#Ouput Final List
print(count)
Name Your File: “ICS3UbigNumber.py”
Write a program that gets a really really big number such as 837183830173638271638163282632 from the user and displays the sum of all the digits
#Read the number as a string not an int
bigNumber = input("Enter the big number: ")
#Loop through each character in the string, convert to int and add
total = 0
for i in range(0,len(bigNumber)):
total = total + int(bigNumber[i])
print("Sum of the digits is", total)
Name Your File: “ICS3Uexceptional.py”
Generate a random list of 150 integers between 25 and 75. Calculate the Standard Deviation of the List. Ask the user for an integer and determine if its exceptional or not. You cannot use any built in statistical functions that python has for lists (sum, max, min, average, standard deviation, etc).
The standard deviation is a measure of how spread out a list of data is. To calculate the standadrd deviation:
In most normal situations most of the data would fall within 1 standard deviation. If it doesn’t fall inside 1 standard deviation it is considered exceptional.
For example, if a class has an average of 75 and the standard deviation is 15, then that indicates that any student who has an average above 90 (75+15) or below 60 (75-15) is somehow exceptional compared to the rest of the class.
import random
import math
#Generate the random list
x = []
for i in range(0,150):
x.append(random.randint(25,75))
#Calculate the average
total = 0
for i in range(0,150):
total = total + x[i]
u = total/150
#Calculate the squared error
error = []
for i in range(0,150):
error.append((x[i]-u)**2)
#Calculate the average of the error
total = 0
for i in range(0,150):
total = total + error[i]
v = total/150
#Calculate the standard deviation
std = math.sqrt(v)
#Display info
print("The average of your list is",round(u,2))
print("The standard deviation of the list is",round(std,2))
#Check if number is exceptional
num = int(input("Enter the number to check: "))
high = u + std
low = u - std
if num >= low and num <= high:
print("Not Exceptional")
else:
print("Exceptional")
Name Your File: “ICS3Upalindrome.py”
Write a program that checks if a single word entered from the user is a palindrome. Don’t use the built in “String Reverse” function python has.
#get word
word = input("Enter the word: ")
#create the reverse word
letter = len(word)-1
reverse = ""
while letter >= 0:
reverse = reverse + word[letter]
letter = letter - 1
#Check for palindrome
if word == reverse:
print("Palindrome")
else:
print("Not Palindrome")
Name Your File: “ICS3UrotateList.py”
Write a program that asks the user to enter the values for a list. The information is to be entered all on one line. Ask the user how much they want to shift the values over by? Display the shifted list
#Get user input and split the string into a list
c = input("Enter list values all on one line, separated by space\n")
values = c.split()
#get the length
length = len(values)
#get the shift value
shift = int(input("Enter the shift value: "))
print("\nOriginal Values:\t")
print(values)
#Repeat the single shift the correct number of times
for i in range(0,shift):
#Shift by 1
last = values[length-1]
del values[length-1]
values.insert(0,last)
print("Shifted Values:\t")
print(values)