Python Lists
Learn to create lists, access elements with indexing and slicing, modify lists, and use list comprehensions.
Creating and Accessing Lists
A list is an ordered collection of items enclosed in square brackets []. Lists can hold any data type and are one of the most versatile data structures in Python.
# Creating lists fruits = ["apple", "banana", "cherry", "date"] scores = [85, 92, 78, 95, 88] mixed = ["hello", 42, True, 3.14] empty = [] # Accessing elements (indexing starts at 0) print(fruits[0]) # apple print(fruits[-1]) # date (last item) print(fruits[1:3]) # ['banana', 'cherry'] (slicing) # Length of a list print(len(fruits)) # 4
Modifying Lists
Lists are mutable, meaning you can change them after creation. You can add, remove, and modify elements using built-in methods.
colours = ["red", "green", "blue"]
# Adding items
colours.append("yellow") # Add to end
colours.insert(1, "orange") # Insert at index 1
print(colours) # ['red', 'orange', 'green', 'blue', 'yellow']
# Removing items
colours.remove("green") # Remove by value
popped = colours.pop() # Remove and return last item
print(popped) # yellow
print(colours) # ['red', 'orange', 'blue']
# Modifying items
colours[0] = "purple" # Change first item
print(colours) # ['purple', 'orange', 'blue']
# Sorting
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers) # [1, 1, 3, 4, 5, 9]
List Comprehensions
A list comprehension is a concise way to create a new list by transforming or filtering items from an existing list. It uses the syntax [expression for item in list].
# Create a list of squares squares = [x ** 2 for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] # Filter: only even numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = [n for n in numbers if n % 2 == 0] print(evens) # [2, 4, 6, 8, 10] # Transform: uppercase all strings names = ["alice", "bob", "charlie"] upper_names = [name.upper() for name in names] print(upper_names) # ['ALICE', 'BOB', 'CHARLIE']
Key Vocabulary
List
An ordered, mutable collection of items enclosed in square brackets [].
Index
The position of an element in a list, starting from 0 for the first element.
Mutable
Can be changed after creation. Items can be added, removed, or modified.
List Comprehension
A concise one-line syntax for creating lists: [expr for item in list].
Worked Examples
Calculate the average of a list of scores
scores = [85, 92, 78, 95, 88]
total = sum(scores)
count = len(scores)
average = total / count
print(f"Scores: {scores}")
print(f"Total: {total}")
print(f"Average: {average}")
Step 1: sum() adds all elements, len() counts the elements.
Output: Scores: [85, 92, 78, 95, 88] | Total: 438 | Average: 87.6
Build a shopping list with add and remove
shopping = ["milk", "bread", "eggs"]
print(f"Initial: {shopping}")
# Add items
shopping.append("butter")
shopping.insert(0, "cereal")
print(f"After adding: {shopping}")
# Remove an item
shopping.remove("bread")
print(f"After removing bread: {shopping}")
# Check if item exists
print(f"Is 'milk' in list? {'milk' in shopping}")
Step 1: append() adds to the end; insert(0, ...) adds to the beginning.
Step 2: Use in to check membership. Returns True or False.
Use list comprehension to filter passing scores
all_scores = [45, 82, 67, 91, 38, 75, 53, 88]
# Filter scores >= 50 (passing)
passing = [s for s in all_scores if s >= 50]
failing = [s for s in all_scores if s < 50]
print(f"Passing: {passing}")
print(f"Failing: {failing}")
print(f"Pass rate: {len(passing)}/{len(all_scores)}")
Step 1: The list comprehension filters items based on the if condition.
Output: Passing: [82, 67, 91, 75, 53, 88] | Failing: [45, 38] | Pass rate: 6/8
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
What does ["a", "b", "c"][1] return?
Question 2
Which method adds an item to the end of a list?
Question 3
What does [x * 2 for x in [1, 2, 3]] produce?
Question 4
What does len([10, 20, 30, 40]) return?
Question 5
What does [1, 2, 3][-1] return?
Key Concepts Summary
-
●
Lists are ordered, mutable collections created with
[]. -
●
Access elements with indexing (starts at 0) and slicing
[start:end]. -
●
Key methods:
.append(),.insert(),.remove(),.pop(),.sort(). -
●
Use
len(),sum(), andinto work with lists. -
●
List comprehensions create new lists concisely:
[expr for item in list if condition].