7.1 Introduction to Lists
A list is a Python collection that stores several values inside one variable. Lists keep their items in order and allow you to add, remove, replace, or examine values. A list can hold names, numbers, prices, colors, or even other lists. Lists are useful whenever a program needs to manage a group of related items.
Example
fruits = ["apple", "banana", "orange"]
print(fruits)
Output
['apple', 'banana', 'orange']
Output explanation: Python displays the three strings inside square brackets. The commas separate the items, and the original order is preserved.
7.2 Creating Lists
You create a list by placing values between square brackets and separating the values with commas. The items may share the same data type or use different data types. After assigning the list to a variable, you can print it, update it, loop through it, or pass it to another part of your program.
Example
student = ["Sara", 14, True]
print(student)
Output
['Sara', 14, True]
Output explanation: The list contains a string, an integer, and a Boolean value. Python allows different data types to be stored in the same list.
7.3 Empty Lists
An empty list contains no items when it is first created. You can make one with empty square brackets. Empty lists are useful when a program will collect information later, such as names entered by users, products added to a shopping cart, messages received from a form, or scores calculated while the program is running.
Example
tasks = []
tasks.append("Study Python")
print(tasks)
Output
['Study Python']
Output explanation: The list starts empty. The append method adds one string to the end, so the printed list now contains one task.
7.4 List Items
Every value stored inside a list is called an item or element. Items are separated by commas and can be strings, numbers, Boolean values, or other objects. Duplicate values are allowed. The position of each item matters because Python gives every item an index that can be used to access, replace, or remove it.
Example
values = [10, "hello", 10, False]
print(values)
Output
[10, 'hello', 10, False]
Output explanation: Python keeps every item, including the repeated number 10. Lists allow duplicate values and mixed data types.
7.5 Accessing List Items
To access one list item, write the list name followed by an index inside square brackets. Python indexes begin at zero, so the first item uses index zero. Accessing an item lets you print it, compare it, use it in a calculation, or store it in another variable without changing the original list.
Example
colors = ["red", "green", "blue"]
print(colors[1])
Output
green
Output explanation: Index 1 points to the second item because Python starts counting at zero. Therefore, the selected value is green.
7.6 Positive Indexing
Positive indexing counts list positions from the beginning. The first item is index zero, the second is index one, and the pattern continues. Positive indexes are useful when you know an item’s position from the left side. Remembering that counting begins at zero prevents a common beginner mistake called an off-by-one error.
Example
animals = ["cat", "dog", "bird", "fish"]
print(animals[0])
print(animals[2])
Output
cat
bird
Output explanation: Index 0 selects cat, while index 2 selects bird. The positions are counted as 0, 1, 2, and 3.
7.7 Negative Indexing
Negative indexing counts backward from the end of a list. Index minus one selects the last item, minus two selects the second-last item, and so on. This is convenient when you need an item near the end but do not know the list’s exact length. You do not need to calculate its positive index.
Example
cities = ["Toronto", "Ottawa", "Montreal", "Vancouver"]
print(cities[-1])
print(cities[-2])
Output
Vancouver
Montreal
Output explanation: Minus one selects the last city, Vancouver. Minus two moves one position to the left and selects Montreal.
7.8 List Slicing
List slicing creates a new list containing part of an existing list. A slice commonly uses a start position and a stop position separated by a colon. The start item is included, but the stop item is excluded. Slicing is useful for selecting ranges, dividing data, copying sections, or examining only the items you need.
Example
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
Output
[20, 30, 40]
Output explanation: The slice begins at index 1 and stops before index 4. It therefore contains 20, 30, and 40.
7.9 Changing List Items
Lists are mutable, which means their items can be changed after the list is created. To replace one item, use its index on the left side of an assignment. Python removes the old value at that position and stores the new value there. This is useful for correcting information or updating a user’s selection.
Example
foods = ["pizza", "salad", "soup"]
foods[1] = "pasta"
print(foods)
Output
['pizza', 'pasta', 'soup']
Output explanation: The item at index 1 was salad. The assignment replaces it with pasta while leaving the other items unchanged.
7.10 Changing Multiple Items
You can replace several list items at once by assigning new values to a slice. The selected range is removed and replaced with the new sequence. The number of replacement items does not have to match the original range. This makes it possible to expand, shorten, or update a section of a list in one statement.
Example
letters = ["a", "b", "c", "d"]
letters[1:3] = ["x", "y"]
print(letters)
Output
['a', 'x', 'y', 'd']
Output explanation: The slice at indexes 1 and 2 contained b and c. Those two items are replaced by x and y.
7.11 Adding Items with append()
The append method adds one item to the end of an existing list. It changes the original list and does not create a new list. Append is commonly used when information arrives one item at a time, such as adding a new student, recording another score, or placing another product into a shopping cart.
Example
names = ["Ali", "Mina"]
names.append("Sara")
print(names)
Output
['Ali', 'Mina', 'Sara']
Output explanation: Sara is added after the existing two names because append always places the new item at the end.
7.12 Adding Items with insert()
The insert method adds an item at a specific position. It receives an index and the new value. Existing items at that position and after it move one place to the right. Insert is useful when order matters and the new item must appear at the beginning, middle, or another exact location in the list.
Example
numbers = [10, 30, 40]
numbers.insert(1, 20)
print(numbers)
Output
[10, 20, 30, 40]
Output explanation: The value 20 is inserted at index 1. The previous items 30 and 40 move to later positions.
7.13 Adding Multiple Items with extend()
The extend method adds every item from another iterable to the end of a list. Unlike append, which adds its argument as one item, extend adds the values separately. It is useful for combining an existing list with several new values while changing the original list directly and preserving the order of all added items.
Example
first = [1, 2]
first.extend([3, 4, 5])
print(first)
Output
[1, 2, 3, 4, 5]
Output explanation: The three values from the second list are added individually after 1 and 2.
7.14 Removing Items with remove()
The remove method deletes the first item whose value matches the value you provide. You do not need to know the item’s index. If the value appears more than once, only its first occurrence is removed. If the value is absent, Python raises an error, so programs may check membership before calling remove.
Example
colors = ["red", "blue", "green", "blue"]
colors.remove("blue")
print(colors)
Output
['red', 'green', 'blue']
Output explanation: Only the first blue item is removed. The second blue item remains in the list.
7.15 Removing Items with pop()
The pop method removes an item and returns the removed value. Without an index, it removes the last item. With an index, it removes the item at that position. Pop is helpful when you need both to delete an item and continue using the removed value, such as processing the latest task in a list.
Example
tasks = ["email", "study", "exercise"]
last_task = tasks.pop()
print(last_task)
print(tasks)
Output
exercise
['email', 'study']
Output explanation: Pop removes the last item, stores it in last_task, and leaves the first two tasks in the list.
7.16 Using del
The del statement removes an item or a range of items by index. It can also delete the entire list variable. Unlike pop, del does not return the removed value. Use it when you know the position of data you no longer need. Be careful because using an invalid index causes an IndexError.
Example
numbers = [10, 20, 30, 40]
del numbers[1]
print(numbers)
Output
[10, 30, 40]
Output explanation: The item at index 1 is 20, so del removes it and the later items shift left.
7.17 Clearing Lists
The clear method removes every item from a list but keeps the list variable available. After clearing, the list still exists and can receive new items. This is useful when a program needs to reset collected data, empty a cart, begin a new round of a game, or reuse the same list variable for fresh information.
Example
cart = ["bread", "milk", "eggs"]
cart.clear()
print(cart)
Output
[]
Output explanation: All three items are removed. Empty square brackets show that cart still exists but contains no items.
7.18 Finding List Length
The len function returns the number of items in a list. It is useful for showing totals, checking whether a list is empty, controlling loops, or validating that enough information was entered. The returned value is an integer. Nested lists count as single items at the outer level because each inner list occupies one position.
Example
students = ["Ali", "Sara", "Mina", "John"]
print(len(students))
Output
4
Output explanation: The list contains four names, so len returns the integer 4.
7.19 Checking Membership
The in operator checks whether a value exists in a list, while not in checks whether it is absent. The result is either True or False. Membership tests are useful before removing values, preventing duplicate entries, checking permissions, or confirming that a user’s choice is one of the allowed options.
Example
fruits = ["apple", "banana", "orange"]
print("banana" in fruits)
print("grape" not in fruits)
Output
True
True
Output explanation: Banana exists in the list, and grape does not exist, so both conditions evaluate to True.
7.20 Counting Items
The count method tells you how many times a particular value appears in a list. It returns zero when the value is absent. Count is useful for finding repeated answers, measuring product quantities, checking votes, or summarizing data. The comparison uses exact values, so uppercase and lowercase strings are normally treated as different items.
Example
votes = ["yes", "no", "yes", "yes", "no"]
print(votes.count("yes"))
Output
3
Output explanation: The string yes appears three times, so the count method returns 3.
7.21 Finding Item Positions
The index method returns the position of the first matching value in a list. If the value appears several times, only the first position is returned. If the value does not exist, Python raises a ValueError. Membership can be checked first when the value may be missing. Index positions always begin at zero.
Example
names = ["Ali", "Sara", "Mina"]
position = names.index("Sara")
print(position)
Output
1
Output explanation: Sara is the second item, but its index is 1 because Python begins counting at zero.
7.22 Sorting Lists
The sort method arranges the items in an existing list. Numbers are normally placed from smallest to largest, and strings are ordered alphabetically. Passing reverse=True sorts in descending order. Sort changes the original list. All compared items should normally have compatible types, because Python cannot directly order unrelated values such as strings and integers.
Example
scores = [88, 72, 95, 81]
scores.sort()
print(scores)
Output
[72, 81, 88, 95]
Output explanation: The numbers are rearranged from the smallest value to the largest value.
7.23 Custom Sorting
Custom sorting lets you decide which part of each item Python should use for ordering. The key argument receives a function that produces a comparison value. For beginners, built-in functions such as len are easy to use. Custom sorting is valuable when ordering words by length, records by price, or students by a selected score.
Example
words = ["elephant", "cat", "tiger", "ox"]
words.sort(key=len)
print(words)
Output
['ox', 'cat', 'tiger', 'elephant']
Output explanation: Python uses each word’s length as the sorting key, so the shortest word appears first.
7.24 Reversing Lists
The reverse method changes the order of a list so the last item becomes first and the first item becomes last. It does not sort values by size or alphabet; it only flips the current order. A slice with a negative step can also produce a reversed copy without modifying the original list.
Example
numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers)
Output
[4, 3, 2, 1]
Output explanation: The original order is flipped, so the last number appears first and the first number appears last.
7.25 Copying Lists
Assigning one list variable to another does not create an independent copy. Both names refer to the same list. To make a separate top-level list, use the copy method, list function, or a full slice. This prevents simple changes in one list from unexpectedly changing another list that was supposed to remain separate.
Example
original = [1, 2, 3]
copy_list = original.copy()
copy_list.append(4)
print(original)
print(copy_list)
Output
[1, 2, 3]
[1, 2, 3, 4]
Output explanation: The copied list receives 4, while the original list remains unchanged.
7.26 Shallow Copies
A normal list copy is a shallow copy. It creates a new outer list, but nested mutable objects inside it may still be shared. Changing the outer structure is independent, while changing an inner shared list can appear in both copies. Understanding this behavior is important when lists contain other lists, dictionaries, or mutable objects.
Example
original = [[1, 2], [3, 4]]
copy_list = original.copy()
copy_list[0].append(9)
print(original)
print(copy_list)
Output
[[1, 2, 9], [3, 4]]
[[1, 2, 9], [3, 4]]
Output explanation: Both outer lists refer to the same first inner list, so adding 9 is visible through both variables.
7.27 Joining Lists
Lists can be joined with the plus operator, extend method, or unpacking. The plus operator creates a new list containing the items from both operands. Extend changes the first list. Joining lists is useful when combining results, merging groups, adding imported data, or building one complete sequence from several smaller collections.
Example
morning = ["breakfast", "school"]
evening = ["dinner", "study"]
day = morning + evening
print(day)
Output
['breakfast', 'school', 'dinner', 'study']
Output explanation: The plus operator creates a new list containing all morning items followed by all evening items.
7.28 Nested Lists
A nested list is a list that contains one or more lists as items. Nested lists are helpful for grouped information, tables, game boards, schedules, or categories. To access a value inside an inner list, use one index for the outer list and another index for the position within the selected inner list.
Example
students = [["Ali", 90], ["Sara", 95]]
print(students[1][0])
print(students[1][1])
Output
Sara
95
Output explanation: The first index selects the second inner list. The second index selects Sara and then her score, 95.
7.29 Multidimensional Lists
A multidimensional list represents data using several levels of nested lists. A two-dimensional list resembles rows and columns in a table. More dimensions can represent layers or groups, although deeply nested structures can become difficult to read. Multidimensional lists are used for grids, matrices, seating charts, maps, and simple game boards.
Example
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[2][1])
Output
8
Output explanation: The outer index 2 selects the third row, and the inner index 1 selects the second value in that row.
7.30 List Unpacking
List unpacking assigns list items to separate variables in one statement. The number of variables must normally match the number of items. Unpacking makes code easier to read when a list has a known structure, such as a name, age, and city. Each variable receives the value from the corresponding list position.
Example
person = ["Mina", 25, "Toronto"]
name, age, city = person
print(name)
print(age)
print(city)
Output
Mina
25
Toronto
Output explanation: The first list item goes into name, the second into age, and the third into city.
7.31 Extended Unpacking
Extended unpacking uses an asterisk before one variable so it can collect several remaining items into a new list. This is useful when you need the first item, last item, or another fixed part while grouping the rest together. Only one starred target may appear in a single unpacking assignment.
Example
numbers = [10, 20, 30, 40, 50]
first, *middle, last = numbers
print(first)
print(middle)
print(last)
Output
10
[20, 30, 40]
50
Output explanation: First receives 10, last receives 50, and the starred middle variable collects the remaining values.
7.32 Looping Through Lists
A loop processes list items one at a time. A for loop is the simplest choice when you need every value. You can print items, calculate totals, validate information, or create new results. The loop variable temporarily receives each item in order, so the same indented code runs once for every list element.
Example
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
Output
apple
banana
orange
Output explanation: The loop visits each fruit in order and print runs once for every item.
7.33 List Comprehensions
A list comprehension is a compact way to create a new list from an existing iterable. It combines an expression and a loop inside square brackets. List comprehensions are useful for simple transformations, such as doubling numbers or changing text. Beginners should first understand ordinary loops before using this shorter form.
Example
numbers = [1, 2, 3, 4]
squares = [number ** 2 for number in numbers]
print(squares)
Output
[1, 4, 9, 16]
Output explanation: Each number is raised to the power of two, and every result is collected into a new list.
7.34 Conditional List Comprehensions
A conditional list comprehension creates a new list while keeping only items that satisfy a condition. The condition appears after the loop portion. This is useful for filtering numbers, valid names, available products, or completed tasks. It can replace a simple loop containing an if statement, but clarity should remain more important than shortening code.
Example
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)
Output
[2, 4, 6]
Output explanation: Only numbers whose remainder after division by two is zero are added to the new list.
7.35 Nested List Comprehensions
A nested list comprehension includes more than one loop or creates nested list structures. It can be useful for grids and combinations, but it may become difficult for beginners to read. Start with a clear ordinary nested loop, then use a comprehension only when the meaning remains easy to understand and maintain.
Example
grid = [[row * 3 + column for column in range(3)] for row in range(2)]
print(grid)
Output
[[0, 1, 2], [3, 4, 5]]
Output explanation: The inner comprehension creates each row, and the outer comprehension creates two rows in the final nested list.
7.36 Lists vs Other Collections
Python provides lists, tuples, sets, and dictionaries for different jobs. Lists are ordered, mutable, and allow duplicates. Tuples are ordered but normally unchanged after creation. Sets store unique items without relying on position. Dictionaries connect keys with values. Choosing the correct collection depends on whether order, changes, duplicates, or named access are needed.
Example
items = ["apple", "apple", "banana"]
unique_items = set(items)
print(items)
print(unique_items)
Output
['apple', 'apple', 'banana']
{'apple', 'banana'}
Output explanation: The list keeps order and duplicates. Converting it to a set removes the repeated apple; set display order may vary.
7.37 Common List Errors
Common list errors include using an index that does not exist, removing a missing value, mixing incompatible types during sorting, and accidentally sharing one list between variables. Reading the final line of the traceback usually identifies the error type. Checking length, membership, and data types before an operation can prevent many beginner mistakes.
Example
numbers = [10, 20, 30]
index = 2
if index < len(numbers):
print(numbers[index])
Output
30
Output explanation: The condition confirms that index 2 is valid before accessing the list, so Python safely prints 30.
7.38 Practical List Applications
Lists are used in shopping carts, student records, task managers, menus, search results, game inventories, schedules, and many other applications. A program can collect values, update them, remove finished items, sort results, and calculate summaries. Combining basic list methods provides enough power to build many useful beginner projects.
Example
prices = [4.50, 2.25, 6.00]
total = sum(prices)
print(f"Total: ${total:.2f}")
Output
Total: $12.75
Output explanation: The sum function adds all three prices. The formatted string displays the total with exactly two decimal places.
7.39 Chapter Practice Exercises
Practice helps you remember how list operations work. Try creating lists, accessing positive and negative indexes, slicing ranges, replacing values, adding and removing items, sorting data, copying lists, looping through values, and writing comprehensions. Run every exercise, compare the output with your expectation, and correct mistakes by reading Python’s error messages carefully.
Example
numbers = [5, 2, 8, 2]
numbers.append(10)
numbers.remove(2)
numbers.sort()
print(numbers)
print(len(numbers))
Output
[2, 5, 8, 10]
4
Output explanation: Append adds 10, remove deletes the first 2, sort arranges the remaining values, and len reports four items.
7.40 Chapter Mini Project
This mini project creates a simple shopping list manager using the list skills from this chapter. It begins with an empty list, adds products, removes one product, sorts the remaining items, and prints each item with a number. A larger version could accept user input, prevent duplicates, save data, or mark purchased items.
Example
shopping_list = []
shopping_list.append("Milk")
shopping_list.append("Bread")
shopping_list.append("Apples")
shopping_list.remove("Bread")
shopping_list.sort()
print("Shopping List")
for number, item in enumerate(shopping_list, start=1):
print(f"{number}. {item}")
Output
Shopping List
1. Apples
2. Milk
Output explanation: Bread is added and then removed. The remaining items are sorted alphabetically, and enumerate numbers them starting at one.