ICS3U Python Lists and Strings

ICS3U Learning Goals

In this ICS3U Grade 11 Computer Science lesson you will be learning to:

  • Store data using a list
  • Access the data in a list and String using index values
  • Use loops to efficiently access and modify values in a list and String

Data Structures

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

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.  

Defining and Printing Lists

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]
				
			

Interactive Learning Activity - Grade 11 Computer Science

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")
				
			

Accessing Data Within a List

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"]

				
			
  • “Teacher” is stored in index 0
  • “Student” is stored in index 1
  • “Parent” is stored in index 2
  • “Principal” is stored in index 3
  • “Caretaker” is stored in index 4
You can access the values in the list using the list name and putting the index you want to access inside square brackets [ ].  They just act exactly like regular variables that you can manipulate and use in the rest of your program.
				
					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]

				
			

Interactive Learning Activity - Grade 11 Computer Science

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])
				
			

Finding the length of a list

It might be helpful to know how many items are in a list, you can use the len statement to accomplish this
				
					people = ["Teacher", "Student", "Parent", "Principal", "Caretaker"]
numbers = [8, 9, 4, 3, -2, 14, 5, -6]

numPeople = len(people)
numNumbers = len(numbers)

				
			

Interactive Learning Activity - Grade 11 Computer Science

Finding a Random Value in a list

There are a few different ways to accomplish this task.

  • Generate a random number between 0 and the length of the list – 1 to represent the index, then accessing the list with that variable
  • Use the choice function in the random library

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)




				
			

Using Loops with Lists

The fact that lists keep an ordered version of its variables is extremely useful.

  • That means that a loop counter variable can be used to represent the index value of a list and cycle through each item each time the loop executes.
  • The counter will need to start at 0 and end with the length of the list  – 1. 
  • This is perfectly setup to use a for loop because its range is exclusive of the value entered
  • In the example below, the counter “i” will be used as the index value 
				
					
for i in range(0,len(listName))
				
			

Interactive Learning Activity - Grade 11 Computer Science

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])



				
			
  • Modify the code to print all on the same line separated by spaces
  • Modify the code to print all on the same line separated by commas (Don’t allow a comma to be printed after the last item)

The value of i starts at 0

  • The program prints myNumbers[0] which is the number 4

The value of i then increases to 1

  • The program prints myNumbers[1] which is the number 8

The value of i then increases to 2

  • The program prints myNumbers[2] which is the number 15

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])



				
			

Commmon List Functions

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

  • Use a loop to cycle through each value and add them up (like you did in the repetition structure lesson)
  • Python has a built in sum function which accomplishes the same task
				
					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.

  • Use a loop to compare each value to a current max value, and if its larger, then replace that current maximum value with the new one.
  • Python has a built in max function which accomplishes the same task

Interactive Learning Activity - Grade 11 Computer Science

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)
				
			
  • Try to modify the code so that it finds the minimum value in the list
  • Can you guess what the built in function for the minimum might be?

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])

  • The loop compares 8 to 4 and since 8 > 4, it sets theMax to 8 and moves to the next number in the list
  • Now 3 is compared to 8 and  3 is not > 8 so the if statement doesn’t execute and loop starts again.
  • Now 36 is compared to 8.  36 > 8 so theMax is set to 36
  • Now 17 is compared to 36.  It is not greater than so the if statement is skipped

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)
				
			

Modifying Values in a List

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.

Interactive Learning Activity - Grade 11 Computer Science

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)
				
			

Interactive Learning Activity - Grade 11 Computer Science

Deleting Existing Values

There are several different functions that can be used to remove items from a list

  • del
  • pop
  • clear
  • remove

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)

				
			

Interactive Learning Activity - Grade 11 Computer Science

Adding Values into the list

You can add items to the end of the list or insert them at an index of choosing

  • append
  • insert

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)
				
			

Interactive Learning Activity - Grade 11 Computer Science

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)
				
			

Video Summary

Watch a video of your teacher summarizing the learning content for this section

Play Video

Extra Examples

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.  

Strings

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.

Accessing Characters

If you want to access the individual characters in a String

  • Use the String name, its index, and [ ]. Just like using a list
  • The character you get is still treated as String. There are no character data types in python
				
					word = "snake"

#Stores the letter s in the variable
firstLetter = word[0]

				
			

Length of a String

The length of a String is found the same way as the length of a list.

				
					word = "snake"

numLetters = len(word)

				
			

Joining Strings

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

				
			

Interactive Learning Activity - Grade 11 Computer Science

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)
				
			
  • Modify the code so that your program can take a list of characters and create a String out of them

Let’s say the user entered the letters 

  • h
  • e
  • l
  • l
  • o

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)
				
			

Splitting Strings

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

Interactive Learning Activity - Grade 11 Computer Science

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])
				
			

Splicing Strings

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:]
				
			

Upper and Lower Case Conversions

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

				
			

Counting Occurrences

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")
				
			

Video Summary

Watch a video of your teacher summarizing the learning content for this section

Play Video

ICS3U Coding Questions

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:

  • A video of your teacher live coding and explaining the solution
  • The final code used in the video.

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.

ICS3U Practice Question

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")
				
			

ICS3U Practice Question

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.

  • Don’t use 26 count statements.  Store all the letters in a String
    • “abcdefghijklmnopqrstuvwxyz”
  • Use a loop to cycle through them with a count statement inside

				
					#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)
				
			

ICS3U Practice Question

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

  • Hint: Read the data as a String, not as a number.

				
					#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)
				
			

ICS3U Practice Question

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:

  • Assume the data is in a list x[0], x[1], x[2], etc..
  • Find the average of all the numbers, call it u
  • Find the squared error between the data points and the average (Make a new list of the square of the differences between each of the data points and the average) (x[0] – u)^2, (x[1] – u)^2, etc
  • Find the average of that new list, call it v
  • Finally, the standard deviation is the square root of v

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")


				
			

ICS3U Practice Question

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")


				
			

ICS3U Practice Question

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

ICS3U List Rotate

				
					#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)

				
			

External Resources for Strings

Return to ICS3U1 Main Page