Lists, loops, conditionals, and functions#
Learning objectives
By the end of this lab, you will be able to:
Create and manipulate lists in Python
Access list elements using indexing and slicing
Work with nested lists (lists of lists)
Use for loops to iterate over lists
Use if-else-elif statements for complex decision-making
Define your own functions with parameters and return values
Combine lists, loops, conditionals, and functions to solve problems
Part 1: Lists in Python#
What is a list?#
A list is an ordered, mutable collection of items. It can contain items of any type (integers, floats, strings, booleans, even other lists), and items can be repeated.
Think of a list like a shelf: objects are arranged in a specific order, you can add or remove them, and the same object can appear multiple times. It can also hold different kinds of objects: books can stand next to action figures, just as a list can mix items of different types.
Creating lists#
There are two main ways to create lists:
# Method 1: Using the list() constructor
empty_list = list()
print(empty_list) # []
# list() can also build a list from a string, one item per character
letters = list("Kant")
print(letters) # ['K', 'a', 'n', 't']
[]
['K', 'a', 'n', 't']
# Method 2: Using square brackets (more common)
philosophers = ["Socrates", "Plato", "Aristotle"]
print(philosophers)
['Socrates', 'Plato', 'Aristotle']
# Lists can contain different types
mixed_list = ["Kant", 1724, True, 3.14]
print(mixed_list)
['Kant', 1724, True, 3.14]
# Lists can contain duplicates
arguments = ["premise", "premise", "conclusion"]
print(arguments)
['premise', 'premise', 'conclusion']
Creating lists of numbers with range()#
range() produces a sequence of whole numbers:
# range(stop) counts from 0 up to stop
print(list(range(5))) # [0, 1, 2, 3, 4]
# range(start, stop) counts from start up to stop
print(list(range(1, 6))) # [1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
The stop number is excluded
range(1, 6) stops at 5, one before the stop number. Slicing, which you will meet later in this lab, follows the same rule.
Adding elements to lists#
# append() adds one item to the end
schools = ["Rationalism", "Empiricism"]
schools.append("Existentialism")
print(schools) # ['Rationalism', 'Empiricism', 'Existentialism']
['Rationalism', 'Empiricism', 'Existentialism']
# extend() adds multiple items from another list
continental = ["Phenomenology", "Hermeneutics"]
schools.extend(continental)
print(schools)
['Rationalism', 'Empiricism', 'Existentialism', 'Phenomenology', 'Hermeneutics']
# insert() adds an item at a specific position
schools.insert(0, "Pre-Socratic") # Insert at beginning (position 0)
print(schools)
['Pre-Socratic', 'Rationalism', 'Empiricism', 'Existentialism', 'Phenomenology', 'Hermeneutics']
Removing elements from lists#
# remove() removes the first occurrence of a value
arguments = ["premise", "fallacy", "premise", "conclusion"]
arguments.remove("fallacy")
print(arguments) # ['premise', 'premise', 'conclusion']
['premise', 'premise', 'conclusion']
If the value is not in the list, remove() raises an error (ValueError: list.remove(x): x not in list) and the program stops.
# pop() removes and returns the last item (or item at index)
thinkers = ["Descartes", "Spinoza", "Leibniz"]
last = thinkers.pop()
print(f"Removed: {last}")
print(f"Remaining: {thinkers}")
Removed: Leibniz
Remaining: ['Descartes', 'Spinoza']
# pop(index) removes item at specific position
thinkers = ["Descartes", "Spinoza", "Leibniz"]
second = thinkers.pop(1) # Remove item at index 1
print(f"Removed: {second}")
print(f"Remaining: {thinkers}")
Removed: Spinoza
Remaining: ['Descartes', 'Leibniz']
pop() also raises an error and stops the program in two cases: when the list is empty (IndexError: pop from empty list) and when the index does not exist (IndexError: pop index out of range).
Exercise: reshape a reading list
Start from reading_list = ["Plato", "Kant", "Hegel", "Marx"] and turn it into ["Socrates", "Plato", "Hegel", "Nietzsche"]. Use append(), insert(), remove(), and pop() once each, and print the list after every step.
Solution
reading_list = ["Plato", "Kant", "Hegel", "Marx"]
reading_list.insert(0, "Socrates")
print(reading_list) # ['Socrates', 'Plato', 'Kant', 'Hegel', 'Marx']
reading_list.remove("Kant")
print(reading_list) # ['Socrates', 'Plato', 'Hegel', 'Marx']
reading_list.pop()
print(reading_list) # ['Socrates', 'Plato', 'Hegel']
reading_list.append("Nietzsche")
print(reading_list) # ['Socrates', 'Plato', 'Hegel', 'Nietzsche']
List length#
# len() returns the number of items
philosophers = ["Hume", "Berkeley", "Locke"]
count = len(philosophers)
print(f"Number of British Empiricists: {count}")
Number of British Empiricists: 3
Accessing list elements (indexing)#
Lists are zero-indexed, meaning the first element is at position 0:
virtues = ["Wisdom", "Courage", "Temperance", "Justice"]
print(virtues[0]) # First element: Wisdom
print(virtues[1]) # Second element: Courage
print(virtues[3]) # Fourth element: Justice
Wisdom
Courage
Justice
# Negative indices count from the end
print(virtues[-1]) # Last element: Justice
print(virtues[-2]) # Second-to-last: Temperance
Justice
Temperance
Changing list elements#
Indexing also works on the left of =: assigning a value to a position replaces the element stored there.
virtues = ["Wisdom", "Courage", "Temperance", "Justice"]
virtues[2] = "Moderation"
print(virtues) # ['Wisdom', 'Courage', 'Moderation', 'Justice']
['Wisdom', 'Courage', 'Moderation', 'Justice']
Swapping two elements#
Swapping means exchanging the elements at two positions. Two assignments alone are not enough, because the first one destroys a value:
virtues = ["Wisdom", "Courage", "Temperance", "Justice"]
virtues[0] = virtues[1]
virtues[1] = virtues[0]
print(virtues) # ['Courage', 'Courage', 'Temperance', 'Justice']
['Courage', 'Courage', 'Temperance', 'Justice']
The first assignment overwrites “Wisdom” before anything has saved it; the second copies “Courage” back to where it already was. Storing one element in a temporary variable first solves the problem:
virtues = ["Wisdom", "Courage", "Temperance", "Justice"]
temp = virtues[0]
virtues[0] = virtues[1]
virtues[1] = temp
print(virtues) # ['Courage', 'Wisdom', 'Temperance', 'Justice']
['Courage', 'Wisdom', 'Temperance', 'Justice']
How the swap works
temp = virtues[0]saves “Wisdom”virtues[0] = virtues[1]copies “Courage” to position 0virtues[1] = tempputs the saved “Wisdom” at position 1
List slicing#
Slicing extracts a portion of a list using [start:end] (end is not included):
philosophers = ["Thales", "Anaximander", "Anaximenes", "Heraclitus", "Parmenides"]
# Get first 3 elements
first_three = philosophers[0:3]
print(first_three) # ['Thales', 'Anaximander', 'Anaximenes']
['Thales', 'Anaximander', 'Anaximenes']
# Shorthand: omit start to begin from beginning
first_three = philosophers[:3]
print(first_three)
['Thales', 'Anaximander', 'Anaximenes']
# Omit end to go until the end
from_third = philosophers[2:]
print(from_third) # ['Anaximenes', 'Heraclitus', 'Parmenides']
['Anaximenes', 'Heraclitus', 'Parmenides']
Question
When you omit end, which index does Python use in its place?
# Get middle elements
middle = philosophers[1:4]
print(middle) # ['Anaximander', 'Anaximenes', 'Heraclitus']
['Anaximander', 'Anaximenes', 'Heraclitus']
# Use negative indices in slicing
last_two = philosophers[-2:]
print(last_two) # ['Heraclitus', 'Parmenides']
['Heraclitus', 'Parmenides']
Exercise: predict indexing and slicing
philosophers = ["Thales", "Anaximander", "Anaximenes", "Heraclitus", "Parmenides"]
print(philosophers[-1])
print(philosophers[1:3])
print(philosophers[:-2])
print(philosophers[3:10])
print(philosophers[5])
Solution
Parmenides
['Anaximander', 'Anaximenes']
['Thales', 'Anaximander', 'Anaximenes']
['Heraclitus', 'Parmenides']
IndexError: list index out of range
A negative
endin a slice counts from the end, just like a negative index:[:-2]takes everything except the last two items.A slice can go past the end of the list:
[3:10]stops at the last item without any error.A single index must exist: the list has five items, at positions 0 to 4, so
[5]raises an error and stops the program.
Other useful list methods#
# count() returns how many times a value appears
premises = ["All humans are mortal", "Socrates is human", "All humans are mortal"]
count = premises.count("All humans are mortal")
print(f"This premise appears {count} times")
This premise appears 2 times
# index() returns the position of first occurrence
schools = ["Stoicism", "Epicureanism", "Skepticism"]
position = schools.index("Epicureanism")
print(f"Epicureanism is at index {position}")
Epicureanism is at index 1
# sort() arranges items in order (modifies the list)
thinkers = ["Zeno", "Aristotle", "Plato", "Socrates"]
thinkers.sort()
print(thinkers) # Alphabetically sorted
['Aristotle', 'Plato', 'Socrates', 'Zeno']
# reverse() reverses the order (modifies the list)
thinkers.reverse()
print(thinkers)
['Zeno', 'Socrates', 'Plato', 'Aristotle']
# sorted() returns a new sorted list and leaves the original unchanged
stoics = ["Seneca", "Epictetus", "Marcus Aurelius"]
ordered_stoics = sorted(stoics)
print(ordered_stoics) # ['Epictetus', 'Marcus Aurelius', 'Seneca']
print(stoics) # ['Seneca', 'Epictetus', 'Marcus Aurelius']
['Epictetus', 'Marcus Aurelius', 'Seneca']
['Seneca', 'Epictetus', 'Marcus Aurelius']
# reverse=True sorts in descending order, with both sort() and sorted()
print(sorted(stoics, reverse=True)) # ['Seneca', 'Marcus Aurelius', 'Epictetus']
stoics.sort(reverse=True)
print(stoics) # ['Seneca', 'Marcus Aurelius', 'Epictetus']
['Seneca', 'Marcus Aurelius', 'Epictetus']
['Seneca', 'Marcus Aurelius', 'Epictetus']
Exercise: predict the order
print(sorted(["plato", "Aristotle", "Zeno", "socrates"]))
print(sorted([3.14, 1724, -5, 0]))
print(sorted([True, 2, False, 0.5]))
print(sorted(["Kant", 1724]))
Solution
['Aristotle', 'Zeno', 'plato', 'socrates']
[-5, 0, 3.14, 1724]
[False, 0.5, True, 2]
TypeError: '<' not supported between instances of 'int' and 'str'
Strings are compared character by character, and every uppercase letter comes before every lowercase letter. So
"Zeno"comes before"plato".Integers and floats are compared by their numeric value.
Booleans count as numbers:
Falseis0andTrueis1.Python cannot compare a string with a number, so sorting a list that mixes them raises an error and stops the program.
Checking if an item is in a list#
# Use 'in' operator
virtues = ["Wisdom", "Courage", "Temperance", "Justice"]
print("Wisdom" in virtues) # True
print("Prudence" in virtues) # False
print("Justice" not in virtues) # False
True
False
False
Exercise: search a list
texts = ["Republic", "Ethics", "Republic", "Meditations"]
print(texts.count("Republic"))
print(texts.index("Republic"))
print("Leviathan" in texts)
print(texts.count("Leviathan"))
print(texts.index("Leviathan"))
Solution
2
0
False
0
ValueError: 'Leviathan' is not in list
index()returns only the position of the first occurrence, even when the value appears more than once.When the value is missing,
count()returns0, whileindex()raises an error and stops the program. Useinfirst if you are not sure the value is there.
Nested lists (lists of lists)#
Lists can contain other lists as elements. This is useful for representing structured data where each item has multiple related fields.
# Storing film information
# Each film is a list with [title, director, year]
films = [
["Blade Runner", "Scott", 1982],
["2001: A Space Odyssey", "Kubrick", 1968],
["The Elephant Man", "Lynch", 1980],
["Den Stygge Stesøsteren", "Blichfeldt", 2025]
]
# Access the first film
print(films[0]) # ['Blade Runner', 'Scott', 1982]
# Access the title of the first film
print(films[0][0]) # Blade Runner
# Access the director of the second film
print(films[1][1]) # Kubrick
# Access the year of the fourth film
print(films[3][2]) # 2025
['Blade Runner', 'Scott', 1982]
Blade Runner
Kubrick
2025
Understanding double indexing
When you have a nested list like films = [["Title", "Director", 2020]]:
films[0]returns the first film (which is a list):["Title", "Director", 2020]films[0][1]first getsfilms[0](the first film), then gets index[1](the director):"Director"
Think of it as: “go to film 0, then get element 1 of that film”
Exercise: explore the film list
Using the films list above, write code that:
Prints the director of “The Elephant Man”
Prints the title of the last film, using a negative index
Adds
["Stalker", "Tarkovsky", 1979]to the end of the list, then prints how many films the list containsPrints the first two films, using slicing
Solution
# 1. "The Elephant Man" is the third film (index 2), the director is at index 1
print(films[2][1]) # Lynch
# 2. -1 is the last film, the title is at index 0
print(films[-1][0]) # Den Stygge Stesøsteren
# 3. append() adds the whole film as a single item
films.append(["Stalker", "Tarkovsky", 1979])
print(len(films)) # 5
# 4. [:2] takes the films at index 0 and 1
print(films[:2]) # [['Blade Runner', 'Scott', 1982], ['2001: A Space Odyssey', 'Kubrick', 1968]]
Part 2: Conditional statements (if-else-elif)#
Review: Basic if-else#
You learned about if and else in the lectures. Let’s review quickly:
age = 18
if age >= 18:
print("You can vote in Italy")
else:
print("You cannot vote in Italy yet")
You can vote in Italy
Introducing elif#
When you have more than two possibilities, use elif (short for “else if”):
language = "Italian"
if language in ["Latin", "Italian", "French", "Spanish", "Portuguese"]:
print("Romance language")
elif language in ["English", "German", "Dutch", "Swedish"]:
print("Germanic language")
elif language in ["Russian", "Polish", "Czech"]:
print("Slavic language")
elif language in ["Greek", "Armenian"]:
print("Hellenic language")
else:
print("Other language family")
Romance language
How elif works
Python checks conditions from top to bottom and executes the first block where the condition is True. Once a block executes, Python skips all remaining elif and else blocks.
Conditionals with lists#
# Check if a list is empty
arguments = []
if len(arguments) == 0:
print("No arguments provided")
else:
print(f"Found {len(arguments)} arguments")
No arguments provided
# Alternative: empty lists are "falsy" in Python
arguments = []
if arguments:
print("Arguments found")
else:
print("No arguments")
No arguments
# Check list length
premises = ["All humans are mortal", "Socrates is human"]
if len(premises) < 2:
print("Need at least 2 premises for a syllogism")
elif len(premises) == 2:
print("Valid syllogism structure")
else:
print("More than 2 premises - complex argument")
Valid syllogism structure
# Check if item is in list
argument_type = "Ad hominem"
fallacies = ["Ad hominem", "Straw man", "False dilemma"]
if argument_type in fallacies:
print(f"'{argument_type}' is a logical fallacy")
else:
print(f"'{argument_type}' is not in the fallacy list")
'Ad hominem' is a logical fallacy
Nested conditionals#
You can put conditionals inside other conditionals:
author = "Moretti, F."
year = 2005
title = "Graphs, Maps, Trees"
if author:
if year:
if title:
print(f"Complete APA reference: {author} ({year}). {title}")
else:
print("Missing title")
else:
print("Missing publication year")
else:
print("Missing author")
Complete APA reference: Moretti, F. (2005). Graphs, Maps, Trees
Combining conditions with logical operators#
# AND: both conditions must be True
age = 25
has_degree = True
if age >= 18 and has_degree:
print("Eligible to apply for graduate program")
else:
print("Not eligible")
Eligible to apply for graduate program
# OR: at least one condition must be True
language = "Greek"
if language == "Greek" or language == "Latin":
print("Classical language")
else:
print("Modern language")
Classical language
# Complex combinations
argument_length = 5
has_premises = True
has_conclusion = True
if argument_length >= 3 and has_premises and has_conclusion:
print("Argument structure is complete")
elif not has_premises:
print("Missing premises")
elif not has_conclusion:
print("Missing conclusion")
else:
print("Argument too short")
Argument structure is complete
Exercise: leap years
In the Gregorian calendar, a year is a leap year when it is divisible by 4. Years divisible by 100 are the exception: they are not leap years, unless they are also divisible by 400.
Store a year in a variable and print Leap year or Not a leap year. Test your code with 2024, 2023, 1900 and 2000.
Solution
year = 1900
if year % 400 == 0:
print("Leap year")
elif year % 100 == 0:
print("Not a leap year")
elif year % 4 == 0:
print("Leap year")
else:
print("Not a leap year")
The checks run from the most specific rule to the most general. If year % 4 == 0 came first, 1900 would print Leap year, because Python would stop at that branch before it reached the exception for centuries.
The same rule also fits in a single condition:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("Leap year")
else:
print("Not a leap year")
Truthy and falsy values shorten it further. A remainder of 0 is falsy and any other remainder is truthy: not year % 4 is therefore True when the year is divisible by 4, and year % 100 alone counts as True when it is not divisible by 100.
if (not year % 4 and year % 100) or not year % 400:
print("Leap year")
else:
print("Not a leap year")
Part 3: Iterating with for loops#
What is a for loop?#
A for loop allows you to go through each element in a list and perform an action with it.
# Basic for loop
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
apple
banana
orange
How for loops work
The for loop takes each element from the list, one at a time, and assigns it to the variable after for. Then it executes the indented code block:
fruit = "apple", prints “apple”fruit = "banana", prints “banana”fruit = "orange", prints “orange”
For loops with conditionals#
# Search for an item
authors = ["Austen", "Dickens", "Woolf", "Orwell"]
for author in authors:
if author == "Woolf":
print(f"Found {author}!")
Found Woolf!
Tracking positions with enumerate()#
The previous loop tells you that Woolf is in the list, but not where. The enumerate() function pairs each element with its position:
authors = ["Austen", "Dickens", "Woolf", "Orwell"]
for position, author in enumerate(authors):
if author == "Woolf":
print(f"Found {author} at position {position}!")
Found Woolf at position 2!
How enumerate() works
At each step, enumerate() hands the loop two values: the position of the element, counted from 0, and the element itself. The two variables after for receive them in that order:
position = 0,author = "Austen"position = 1,author = "Dickens"position = 2,author = "Woolf", prints “Found Woolf at position 2!”position = 3,author = "Orwell"
Exercise: FizzBuzz
For each number from 1 to 15, print:
Fizzif the number is divisible by 3the number itself if it is divisible by neither 3 nor 5
Buzzif it is divisible by 5FizzBuzzif it is divisible by both 3 and 5
Solution
for number in range(1, 16):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
The order of the conditions matters. Python runs only the first branch whose condition is True. Since every number divisible by both 3 and 5 is also divisible by 3, checking number % 3 == 0 first would make 15 print Fizz, and the FizzBuzz branch would never run. The most specific condition therefore has to come first.
Part 4: Defining functions#
What are functions?#
Functions are reusable blocks of code that perform a specific task. They help you:
Organize code into logical units
Avoid repeating the same code
Make code easier to read and maintain
Basic function syntax#
# Define a function with def keyword
def greet():
print("Hello, World!")
# Call the function
greet()
Hello, World!
Important: Defining vs calling a function
Defining a function does NOT execute it! When you write def greet():, Python simply remembers the function exists. Nothing happens until you call (invoke) the function by writing greet() with parentheses.
Think of it like writing a recipe: defining the function is writing down the recipe, calling the function is actually cooking the dish.
Functions with parameters#
Parameters allow you to pass data into functions:
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Silvio")
greet_person("Ivan")
Hello, Silvio!
Hello, Ivan!
# Multiple parameters
def describe_book(title, author, year):
print(f"'{title}' by {author} was published in {year}")
describe_book("Pride and Prejudice", "Jane Austen", 1813)
describe_book("1984", "George Orwell", 1949)
'Pride and Prejudice' by Jane Austen was published in 1813
'1984' by George Orwell was published in 1949
Parameter order matters!
When calling a function, the order of arguments matters. Python matches arguments to parameters by position:
describe_book("1984", "George Orwell", 1949)passes the arguments in the correct orderdescribe_book(1949, "1984", "George Orwell")passes them in the wrong order
You can avoid order issues by using named arguments:
describe_book(year=1949, title="1984", author="George Orwell")
With named arguments, order doesn’t matter because you explicitly specify which value goes to which parameter.
Functions with return values#
Use return to send a value back to the caller:
def add_one(n):
return n + 1
result = add_one(41)
print(result)
42
Functions always return something
Every function returns a value, even if you don’t specify return. If you don’t use return, the function automatically returns None.
def greet():
print("Hello!")
result = greet() # Prints "Hello!" but returns None
print(result) # None
When you want to use the result of a function elsewhere in your code, you must explicitly return a value.
def calculate_years(start_year, end_year):
return end_year - start_year
years = calculate_years(1800, 1850)
print(f"Period duration: {years} years")
Period duration: 50 years
Documenting functions with docstrings#
def calculate_average(numbers):
"""
Calculate the arithmetic mean of a list of numbers.
Parameters:
numbers (list): A list of numeric values
Returns:
float: The average of the numbers
"""
total = sum(numbers)
count = len(numbers)
return total / count
scores = [85, 90, 78, 92]
average = calculate_average(scores)
print(f"Average score: {average}")
Average score: 86.25
Why use docstrings?
Docstrings (triple-quoted strings right after def) document what your function does, what parameters it expects, and what it returns. This helps others (and your future self) understand your code.
Part 5: Hands-on exercise#
Library manager#
Create a program that manages a personal library of books.
Setup:
Create a new file: library_manager.py
Requirements:
Create an empty list
libraryDefine
add_book(library, title, author, year)that creates a book as a list[title, author, year]and adds it to the libraryEach book is stored as a list with 3 elements
Define
find_by_author(library, author)that returns all books by a specific authorDefine
find_by_decade(library, year)that returns all books from the same decade as the given yearFor example, if you pass 1945, it finds books from 1940-1949
Define
print_library(library)that displays all books with numbers
Example usage:
add_book(library, "La Bufera e altro", "Montale", 1956)
add_book(library, "Il Nome della Rosa", "Eco", 1980)
add_book(library, "Se questo è un uomo", "Levi", 1947)
print_library(library)
# Should print numbered list
books_1940s = find_by_decade(library, 1945) # Finds books from 1940-1949
# Should return books from the 1940s decade
Solution
# Create empty library
library = []
def add_book(library, title, author, year):
"""Add a book to the library."""
book = [title, author, year]
library.append(book)
return library
def find_by_author(library, author):
"""Find all books by a specific author."""
found_books = []
for book in library:
if book[1] == author: # book[1] is the author
found_books.append(book)
return found_books
def find_by_decade(library, year):
"""Find all books from the same decade as the given year."""
# Calculate the start of the decade
start_year = (year // 10) * 10
end_year = start_year + 9
found_books = []
for book in library:
book_year = book[2] # book[2] is the year
if start_year <= book_year <= end_year:
found_books.append(book)
return found_books
def print_library(library):
"""Print all books with numbers."""
print("=== Library Contents ===")
counter = 1
for book in library:
print(f"{counter}. {book[0]} by {book[1]} ({book[2]})")
counter += 1
# Add books
add_book(library, "Le Comte de Monte-Cristo", "Dumas", 1844)
add_book(library, "Il Fu Mattia Pascal", "Pirandello", 1904)
add_book(library, "Cristo si è fermato a Eboli", "Levi", 1945)
add_book(library, "Se questo è un uomo", "Levi", 1947)
add_book(library, "La Bufera e altro", "Montale", 1956)
add_book(library, "La Bufera e altro", "Montale", 1956)
add_book(library, "Il Nome della Rosa", "Eco", 1980)
# Display full library
print_library(library)
# Find books by author
print("\n=== Books by Levi ===")
levi_books = find_by_author(library, "Levi")
for book in levi_books:
print(f"{book[0]} by {book[1]} ({book[2]})")
# Find books from 1940s
print("\n=== Books from 1940s ===")
books_1940s = find_by_decade(library, 1945) # Any year in the 1940s
for book in books_1940s:
print(f"{book[0]} by {book[1]} ({book[2]})")
Summary#
In this lab, you learned:
Creating and manipulating lists:
list(),[],range(),append(),extend(),insert(),remove(),pop()Accessing list elements: indexing
[0], negative indices[-1], slicing[start:end]Changing list elements: replacing an element with
list[i] = value, swapping two elements through a temporary variableList methods:
len(),count(),index(),sort(),sorted(),reverse()Nested lists: creating and accessing lists of lists with double indexing
list[0][1]Conditional statements:
if,elif,elseCombining conditions:
and,or,not,inFor loops: iterating over lists with
for item in list:, and over positions and items withfor position, item in enumerate(list):Loops with conditionals: combining
forandifto filter and process dataDefining functions:
def, parameters,returnFunctions with lists and loops: passing lists, iterating, creating new lists
Documentation: docstrings for function documentation
Next lab
The next lab, Algorithm exercises: brute-force, puts linear search and insertion sort into practice.