Python 8a - Using Lists
Lists
A list is a temporary data structure. Any changes made to the list while the program is running will not be saved the next time it is run.
Data can be added to and removed from lists so they can change in size (unlike an array which is fixed and not used in Python).
​
It is important to note that each data element in a list has an index so that it can be specifically referenced (to delete it for example) and that indexes start at 0.
A list of the rainbow colours in order would start at 0 like this:
Creating & Printing Lists
Lists use square brackets in Python. Separate list items with commas.
Strings must use speech marks and integers do not use speech marks.
people = ["Alan", "Jesse", "Max", "Jack"]
years = [2010, 2019, 2001, 2016]
There are many different ways to print items from a list depending on how you want it to look.
Print all items on one line
Type the list name into a print command to output the complete list. Typing an asterisk * before the list name removes punctuation.
cities = ["Shanghai", "Sao Paolo", "Bishkek", "Asmara"]
print(cities)
cities = ["Shanghai", "Sao Paolo", "Bishkek", "Asmara"]
print(*cities)
['Shanghai', 'Sao Paolo', 'Bishkek', 'Asmara']
Shanghai Sao Paolo Bishkek Asmara
Print each item on a separate line
To print a list line-by-line use a for loop to cycle through each item.
​
'city' is just a variable name and can be replaced with the traditional 'i' or anything relevant to the context, such as 'colour' in a list of colours or 'name' in a list of people.
cities = ["Shanghai", "Sao Paolo", "Bishkek", "Asmara"]
for city in cities:
print(city)
Shanghai
Sao Paolo
Bishkek
Asmara
Print separated items on one line
To print separated data elements on the same line then you can use the end command which defines what should go after each item.
​
The example below uses slashes but end = ", " would add comma and space between each element.
cities = ["Shanghai", "Sao Paolo", "Bishkek", "Asmara"]
for city in cities:
print(city, end = " / ")
Shanghai / Sao Paolo / Bishkek / Asmara /
Print specific list items
To print an element with a certain index, put the index in square brackets. But remember that the index starts at 0 not 1.
cities = ["Shanghai", "Sao Paolo", "Bishkek", "Asmara"]
for city in cities:
print("The first city is", cities[0])
print(cities[2], "is the third city")
The first city is Shanghai
Bishkek is the third city
Create a list of five different of foods.
​
Print all list items on one line.
​
Then print each item on a different line.
​
Finally print just the first and fifth items.
Example solution:
lettuce yoghurt tomato artichoke tuna
lettuce
yoghurt
tomato
artichoke
tuna
The first item is lettuce
The fifth item is tuna
Lists Task 1 (Five Foods)
Lists Task 2 (Four Numbers)
Create a list of four integer values.
​​
Print all list items on one line separated by colons.
Example solutions:
345:123:932:758:
812:153:783:603:
Add (Append / Insert) to a List
Append items to the end of a list
To add a new item to the end of a list use the .append() command.​
​
Write .append() after the name of your list, with the new data in brackets.
pets = ["dog", "cat", "hamster"]
pets.append("rabbit")
print(*pets)
fillings = ["ham","cheese","onion"]
extra = input("Enter another filling: ")
fillings.append(extra)
print("Your sandwich:", *fillings)
dog cat hamster rabbit
Enter another filling: lettuce
Your sandwich: ham cheese onion lettuce
Insert items to a specific index
Use the insert command to place an item in a specific position within the list.
Remember that Python counts from 0 so the medals example below puts "silver" as index 2, which is actually the 3rd item.
medals = ["platinum","gold","bronze"]
medals.insert(2,"silver")
print(*medals)
names = ["Stacy","Charli","Jasper","Tom"]
name = input("Enter a name: ")
position = int(input("Enter an index: "))
names.insert(position,name)
print(*names)
platinum gold silver bronze
Enter a name: Lena
Enter an index: 0
Lena Stacy Charli Jasper Tom
Enter a name: Pat
Enter an index: 3
Stacy Charli Jasper Pat Tom
Use a loop to add items to a list
A for loop can be used to add a certain number of items to a list.
A while loop can be used to keep adding values until a certain value (e.g. 'stop' or 'end') is input.
animals = [ ]
​
for i in range(4):
animal = input("Enter an animal: ")
animals.append(animal)
​
print("\nAnimals:" , *animals)
animals = [ ]
while True:
animal = input("Enter an animal: ")
if animal == "stop":
break
else:
animals.append(animal)
print("\nAnimals:" , *animals)
Enter an animal: lion
Enter an animal: horse
Enter an animal: hyena
Enter an animal: squirrel
​
Animals: lion horse hyena squirrel
Enter an animal: rhino
Enter an animal: gazelle
Enter an animal: deer
Enter an animal: stop
​
Animals: rhino gazelle deer
Example solution:
Lists Task 3 (Favourite Musicicans)
Create a list of three musicians or bands you like.​​ Print the list.
​​​
Then append two new bands using two inputs.​​​ Print the list again.
​
Use the sandwich filling example for help.
Musicians I like: Lana Del Rey Devon Cole Elly Duhé
​
Enter another musician: Charli XCX
Enter another musician: Kenya Grace
​
Musicians I like: Lana Del Rey Devon Cole Elly Duhé Charli XCX Kenya Grace
Lists Task 4 (Missing 7)
Create a list of numbers in order from 1 to 10 but miss out 7.
​
Use the insert command to add 7 in the correct place.
​
Print the list before and after you insert 7.
Example solution:
1 2 3 4 5 6 8 9 10
1 2 3 4 5 6 7 8 9 10
Lists Task 5 ('Land' Countries)
Use a while True loop to input countries that end in 'land' until the word 'finish' is input.
​
Print the list at the end.
​
Note: You do not need to check if the countries entered are correct. There are also more than four.
Example solution:
Enter a country ending in 'land': Iceland
Enter a country ending in 'land': Poland
Enter a country ending in 'land': Switzerland
Enter a country ending in 'land': Thailand
Enter a country ending in 'land': finish
​
Country list: Iceland Poland Switzerland Thailand
Delete (Remove/Pop) from a List
Delete items with a specific value
To delete data with a certain value use the .remove() command, with the value in brackets.
trees = ["fir", "elm", "oak", "yew"]
trees.remove("elm")
print(*trees)
fir oak yew
trees = ["fir", "elm", "oak", "yew"]
tree = input("Select a tree to remove: ")
trees.remove(tree)
print(*trees)
Select a tree to remove: oak
fir elm yew
Delete items with a specific index
To delete data in a specific position in your list use the .pop() command, with the position in the brackets.
​
Remember that indexes start at 0 so .pop(0) removes the first item. Negative values start from the end of the list, so -1 is the final item and -2 is the second last item and so on.
kitchen = ["plate","cup","spoon","jug"]
kitchen.pop(0)
print(*kitchen)
kitchen = ["plate","cup","spoon","jug"]
kitchen.pop(-2)
print(*kitchen)
kitchen = ["plate","cup","spoon","jug"]
index = int(input("Select an index: "))
kitchen.pop(index)
print(*kitchen)
cup spoon jug
plate cup jug
Select an index: 1
plate spoon jug
Delete all items in a list
To delete data in a list use the .clear() command.
insects = ["ant", "bee", "wasp"]
insects.clear()
insects.append("hornet")
print(*insects)
hornet
Lists Task 6 (Day Off)
Example solution:
Create a list with the five week days.
​
Ask the user to input a weekday and remove that day from the list.​ Print the list.
Which day do you want off? Tuesday
Your new days of work: Monday Wednesday Thursday Friday
Lists Task 7 (May and October)
Create a list with the twelve months in order.
​​
Delete May and then October using the pop command by referring to their indexes in the list. Print the list.
​
Note: Be aware the index of each month after May will change when May is popped from the list.
Example solution:
January February March April June July August September November December
Finding the Length of a List
To find the length of a list use the len function.
You can create a separate variable for the length (shown in the first example below) or use the len command directly (second example).
states = ["Maine","Utah","Ohio","Iowa"]
length = len(states)
print("There are", length, "states in the list.")
states = ["Maine","Utah","Ohio","Iowa"]
print("There are", len(states), "states in the list.")
There are 4 states in the list.
Lists Task 8 (Q Words)
Use a while True loop to input words beginning with q until the word 'stop' is entered.
​
Then use len to find the length of the list and print this value.
​
Note: You do not need to check if the entered words actually start with q.
Example solution:
Input a Q word: question
Input a Q word: quick
Input a Q word: quiet
Input a Q word: quandry
Input a Q word: stop
​
You wrote 4 Q words!
Cycle Through List Items
A for loop can be used to cycle through each item in a list. The following examples present some ways that this may be used.
​​
This program uses a for loop to add a word (David) before each list item.
davids = ["Beckham", "Attenborough", "Schwimmer", "Tennant", "Lynch"]
for i in range(5):
print("David" , davids[i])
David Beckham
David Attenborough
David Schwimmer
David Tennant
David Lynch
An if statement can be used within a for loop to check the value of each item. The example below checks how many items are 'medium'.
sizes = ["small", "medium", "small", "large", "medium", "small"]
count = 0
​
for i in range(6):
if sizes[i] == "medium":
count = count + 1
print("There were",count,"medium choices.")
There were 2 medium choices.
The program below uses a while loop to allow entries until 'stop' is input then a for loop to check the value of each item.
​
Because the final length of the list is not known when the program starts, the len command is used in the range of the for loop.
sports = []
fcount = 0
rcount = 0
​
while True:
option = input("Choose football or rugby: ")
sports.append(option)
if option == "stop":
break
for i in range(len(sports)):
if sports[i] == "football":
fcount = fcount + 1
elif sports[i] == "rugby":
rcount = rcount + 1
​
print("\nResults:",fcount,"people chose football and",rcount,"chose rugby.")
Choose football or rugby: rugby
Choose football or rugby: rugby
Choose football or rugby: football
Choose football or rugby: rugby
Choose football or rugby: football
Choose football or rugby: stop
​
Results: 2 people chose football and 3 chose rugby.
Lists Task 9 (Over 25)
Create a list with the following eight numbers: 13, 90, 23, 43, 55, 21, 78, 33
​
Use a for loop to cycle through the list and check if each item is over 25. Use a count variable to increase by 1 if the number is over 25.
​
At the end print how many numbers are over 25 - there are five.
Example solution:
5 numbers are over 25.
Lists Task 10 (Favourite Lesson)
Use a while True loop to keep inputting school subjects until 'done' is entered.
​
Keep a count of how many times 'Maths' is entered.
​
Print the total number of people who entered maths.
Example solution:
Enter a subject: English
Enter a subject: Maths
Enter a subject: Art
Enter a subject: Maths
Enter a subject: History
Enter a subject: done
​
There were 2 people who chose maths.
Sorting Lists
The .sort() command will sort elements in a list into alphabetical order (if a string) or numerical order (if a number).
names = ["Robb","Jon","Sansa","Arya","Bran","Rickon"]
print("Original:" , *names)
​
names.sort()
print("Sorted:" , *names)
Original: Robb Jon Sansa Arya Bran Rickon
Sorted: Arya Bran Jon Rickon Robb Sansa
numbers = [56,98,23,12,45]
numbers.sort()
print(*numbers)
12 23 45 56 98
The .sort() command can be used to sort values in descending order by including reverse = True in the brackets.
names = ["Robb","Jon","Sansa","Arya","Bran","Rickon"]
print("Original:" , *names)
​
names.sort(reverse = True)
print("Sorted:" , *names)
Original: Robb Jon Sansa Arya Bran Rickon
Sorted: Sansa Robb Rickon Jon Bran Arya
numbers = [56,98,23,12,45]
numbers.sort(reverse = True)
print(*numbers)
98 56 45 23 12
Lists Task 11 (Sorted Fruit)
Example solution:
Use a for loop to append six fruits to an empty list.
​
Sort the list into alphabetical order and print it.
Enter a fruit: strawberry
Enter a fruit: kiwi
Enter a fruit: lemon
Enter a fruit: pear
Enter a fruit: orange
Enter a fruit: mango
Sorted fruit: kiwi lemon mango orange pear strawberry
Searching Through Lists
A simple if statement can be used to see if a certain value appears within a list.
names = ["Alex", "Bill", "Charlie", "Darla"]
​
name = input("Enter a name: ")
if name in names:
print("Yes," , name , "is in the list.")
else:
print("Sorry," , name , "is not in the list.")
Enter a name: Bill
Yes, Bill is in the list.
Enter a name: Sadie
Sorry, Sadie is not in the list.
Lists Task 12 (Packed Suitcase)
Example solutions:
Create a list with five items to take on holiday.
​
Ask the user to input an item and use an if statement to check if it is or isn't in the list.
What should I pack? sun cream
I've already packed sun cream
What should I pack? toothpaste
Whoops! I forgot to pack toothpaste
Calculating the Sum of a List
To calculate the sum of a list of numbers there are two methods.
Using Python's built-in sum function:
numbers = [1,4,2,3,4,5]
print(sum(numbers))
Both methods will result in the same output:
19
Using a for loop to cycle through each number in the list and add it to a total.
numbers = [1,4,2,3,4,5]
​
total = 0
for number in numbers:
total = total + number
print(total)
Lists Task 13 (Sum and Average)
Example solution:
Use a for loop to ask the user to input 5 numbers and append each to a list.
​
Use the sum command to output the total and use it calculate the average.
Enter a number: 6
Enter a number: 7
Enter a number: 6
Enter a number: 9
Enter a number: 4
The total is 32
The average is 6.4
Extending a List
.extend() can be used in a similar way to .append() that adds iterable items to the end of a list.
​
This commands works well with the choice command (imported from the random library) to create a list of characters that can be randomly selected.
​
The code below adds a lowercase alphabet to an empty list and then, depending on the choice of the user, adds an uppercase alphabet too. The choice command is used in a loop to randomly select 5 characters.
Using .extend() to make a random 5-character code
from random import choice
list = []
list.extend("abcdefghijklmnopqrstuvwxyz")
​
upper = input("Include uppercase letters? ")
if upper == "yes":
list.extend("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
​
code = ""
for number in range(5):
letter = choice(list)
code = code + letter
print("Your five character code is" , code)
Possible outputs:
Include uppercase letters? yes
Your five character code is yPfRe
Include uppercase letters? yes
Your five character code is GJuQw
=
Include uppercase letters? no
Your five character code is gberv
Extend treats each character as an indidual item whereas append adds the whole string as a single entity.
​
Most of time append would be used, but extend is suitable for a password program as additional individual characters can be added to a list depending on the parameters (e.g. lowercase letters, uppercase letters, numbers and special characters).
list = []
list.extend("ABCD")
list.extend("EFGH")
print(list)
list = []
list.append("ABCD")
list.append("EFGH")
print(list)
['A','B','C','D','E','F','G','H']
['ABCD' , 'EFGH']
=
=
Practice Task 14
Use the code above (for a 5-character code) to help you make a password generator.
​
Ask the user if they want uppercase letters, numbers and special characters and use the extend command to add them to a list of characters if they type yes (you should extend lowercase characters into an empty list regardless, like in the code above).
​
Use a for loop and the choice command (imported from the random library) to randomly generate a 10-character password.
Example solutions:
Include uppercase letters? yes
Include numbers? yes
Include special characters? yes
Your new password is RjWSbT&gW5
Include uppercase letters? no
Include numbers? yes
Include special characters? no
Your new password is hdf8se9y2w