Python 8a – Using Lists

Create, access, modify, sort, and iterate lists in Python — with step-by-step examples and practice tasks.

Creating and displaying lists

Lists are mutable collections defined with square brackets. You can store strings, numbers, or even mixed types.

names = ["Alice", "Bob", "Charlie", "Dana"]
release_years = [1998, 2005, 2012, 2020]
print(names)
print(*names)  # unpack to print without brackets

Display each item on a new line using a for loop, or keep them on one line with a separator.

cities = ["New York", "Paris", "Tokyo", "Sydney"]
for city in cities:
    print(city)
for city in cities:
    print(city, end=" | ")
print()  # newline

Accessing list items

Use zero-based indexing to access items:

print("First city:", cities[0])
print("Third city:", cities[2])

Practice tasks (with answers)

Task 1 – Create and Display a Food List

Create a list of five foods, then print them (1) on one line, (2) line by line, and (3) first and last only.

foods = ["apple", "banana", "cherry", "date", "elderberry"]
print("All foods:", *foods)
for food in foods:
    print(food)
print("First food:", foods[0])
print("Last food:", foods[-1])

Task 2 – Print Four Numbers with Colons

Create a list of four integers and display them on one line separated by colons.

numbers = [345, 123, 932, 758]
for number in numbers:
    print(number, end=":")
print()

Task 3 – Favourite Musicians

Print three favourites, then ask for two more, append them, and print the updated list.

musicians = ["The Beatles", "Queen", "Nirvana"]
print("Favourite musicians:", *musicians)
extra1 = input("Enter another musician: ")
extra2 = input("Enter one more musician: ")
musicians.append(extra1)
musicians.append(extra2)
print("Updated list:", *musicians)

Task 4 – Insert the Missing 7

Create 1–10 but omit 7, then insert it at the correct index. Show before/after.

numbers = [1, 2, 3, 4, 5, 6, 8, 9, 10]
print("Before inserting 7:", *numbers)
numbers.insert(6, 7)  # index 6 is correct for 7
print("After inserting 7:", *numbers)

Task 5 – 'Land' Countries

Use a while loop to collect countries ending in “land” until the user types “finish”.

countries = []
while True:
    country = input("Enter a country ending with 'land' (or type 'finish' to stop): ")
    if country.lower() == "finish":
        break
    countries.append(country)
print("Country list:", *countries)

Task 6 – Taking a Day Off

Remove the chosen day from a weekdays list and show the remaining workdays.

weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
day_off = input("Which day do you want off? ")
if day_off in weekdays:
    weekdays.remove(day_off)
    print("Your new workdays:", *weekdays)
else:
    print("That day is not in the workweek.")

Task 7 – May and October

Remove May and October by index using pop(). Show before/after.

months = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"]
print("Before removal:", *months)
removed_may = months.pop(4)       # May at index 4
removed_october = months.pop(8)   # October shifts to index 8 after May is removed
print("After removal:", *months)

Task 8 – Count Q Words

Prompt for words starting with “q” until “stop”. Count how many were entered.

q_words = []
while True:
    word = input("Enter a word starting with 'q' (or type 'stop' to end): ")
    if word.lower() == "stop":
        break
    q_words.append(word)
print("You entered", len(q_words), "Q words!")

Task 9 – Count Numbers Over 25

Create eight numbers and count how many are greater than 25.

numbers = [13, 90, 23, 43, 55, 21, 78, 33]
count_over_25 = 0
for num in numbers:
    if num > 25:
        count_over_25 += 1
print(count_over_25, "numbers are over 25.")

Task 10 – Favourite Lesson Counter

Input subjects until “done”. Count how many times “Maths” appears.

maths_count = 0
while True:
    subject = input("Enter a subject (or type 'done' to finish): ")
    if subject.lower() == "done":
        break
    if subject.lower() == "maths":
        maths_count += 1
print("Maths was entered", maths_count, "times.")

Task 11 – Sorted Fruit

Add six fruits to a list, sort alphabetically, and display the result.

fruits = []
for i in range(6):
    fruit = input("Enter a fruit: ")
    fruits.append(fruit)
fruits.sort()
print("Sorted fruit:", *fruits)

Task 12 – Packed Suitcase

Check if an item is already in the suitcase list and print an appropriate message.

suitcase = ["sunscreen", "hat", "swimsuit", "sunglasses", "towel"]
item = input("What should I pack? ")
if item in suitcase:
    print("I've already packed", item)
else:
    print("Whoops! I forgot to pack", item)

Task 13 – Sum and Average

Input 5 numbers into a list, then compute the total and the average.

numbers = []
for i in range(5):
    num = float(input("Enter a number: "))
    numbers.append(num)
total = sum(numbers)
average = total / len(numbers)
print("The total is", total)
print("The average is", average)

Task 14 – Custom Password Generator

Ask about uppercase, digits, symbols; extend a base list and generate a random 10-character password.

from random import choice

chars = []
chars.extend("abcdefghijklmnopqrstuvwxyz")
if input("Include uppercase letters? ").strip().lower() == "yes":
    chars.extend("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
if input("Include digits? ").strip().lower() == "yes":
    chars.extend("0123456789")
if input("Include special characters? ").strip().lower() == "yes":
    chars.extend("!@#$%^&*()")

password = ""
for i in range(10):
    password += choice(chars)
print("Your 10-character password is:", password)
Tips:
  • Use .append(), .insert(), .remove(), and .pop() to modify lists.
  • Sort with .sort() (in-place) or sorted() (returns a new list).