Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 3 · Lists

Lists

On this pageCreating a ListAccessing List ElementsSlicing a ListCombining Lists (Concatenation)Modifying a ListCopying and ReferencesAssigning to SlicesOther Useful FeaturesMeasuring Length with len()Removing Items by Value with remove()Removing Items by Index with pop()Sorting a List with sort()Copying Lists Safely with copy()Nested ListsMini Project — Shopping List Manager

Programs often need several related values: names, grades, or prices. A list stores these values together, so you do not need a separate variable for every item.

A list is an ordered collection of items enclosed in square brackets [ ], where each item is separated by a comma. Lists are flexible: they can store numbers, text, or even a mix of different data types.

Creating a List

A simple list can be made by placing several values inside brackets:

fruits = ["apple", "banana", "cherry"]
print(fruits)
Listing 127 — Creating a List

Output

['apple', 'banana', 'cherry']

Here,fruits contains three strings. Lists can also store numbers or mixed types:

mixed = [10, "hello", 3.14]
print(mixed)
Listing 128 — Creating a List

Output

[10, 'hello', 3.14]

Lists are used whenever a program needs to handle collections that may change over time, such as adding or removing items from a shopping list.

Accessing List Elements

Since lists are ordered, each item has a position called an index. Python counts from zero, so the first element is at position 0.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])   # first element
print(fruits[2])   # third element
Listing 129 — Accessing List Elements

Output

apple
cherry

You can also use negative indexing to access items from the end:

print(fruits[-1])  # last element
Listing 130 — Accessing List Elements

Output

cherry

Slicing a List

Slicing allows you to extract a sublist by specifying a range of indices inside square brackets, separated by a colon :. The slice starts from the first index and goes up to, but does not include, the second one.

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])   # elements from index 1 to 3
Listing 131 — Slicing a List

Output

[20, 30, 40]

Omitting one side of the slice selects from the start or to the end:

print(numbers[:3])   # first three
print(numbers[2:])   # from index 2 onward
Listing 132 — Slicing a List

Output

[10, 20, 30]
[30, 40, 50]

Slicing can be very useful when working with subsets of data, such as selecting only part of a list for display or calculation.

Combining Lists (Concatenation)

Python allows two or more lists to be joined together using the + operator. This process is known as concatenation.

a = [1, 2, 3]
b = [4, 5]
combined = a + b
print(combined)
Listing 133 — Combining Lists (Concatenation)

Output

[1, 2, 3, 4, 5]

Concatenation is essential when merging data from different sources or when collecting results from multiple operations into a single sequence.

Modifying a List

Unlike strings, lists are mutable, meaning their contents can be changed. You can replace elements or add new ones using assignment and built-in methods.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)
Listing 134 — Modifying a List

Output

['apple', 'mango', 'cherry']

To add items, use .append() to add at the end or .insert() to add at a specific position:

fruits.append("orange")
fruits.insert(1, "kiwi")
print(fruits)
Listing 135 — Modifying a List

Output

['apple', 'kiwi', 'mango', 'cherry', 'orange']

To remove items, use .remove() by value or .pop() by index:

fruits.remove("mango")
fruits.pop(2)
print(fruits)
Listing 136 — Modifying a List

Output

['apple', 'kiwi', 'orange']

Copying and References

An important detail about lists in Python is that variables hold references, not copies. Assigning one list to another variable does not make a new list; it simply gives another name to the same list.

rgb = ["Red", "Green", "Blue"]
rgba = rgb     # both variables point to the same list
rgba.append("Alph")
print(rgb)
Listing 137 — Copying and References

Output

['Red', 'Green', 'Blue', 'Alph']

Notice how changing rgba also affected rgb. They are two names for the same list object.

If you really need a new list, you can make a shallow copy by slicing. This creates a new outer list; any mutable items nested inside it would still be shared:

correct_rgba = rgba[:]   # copy the list
correct_rgba[-1] = "Alpha"  # fix spelling
print(correct_rgba)
print(rgba)
Listing 138 — Copying and References

Output

['Red', 'Green', 'Blue', 'Alpha']
['Red', 'Green', 'Blue', 'Alph']

Now, the correction only applied to the new list, leaving the original unchanged.

Assigning to Slices

Lists allow you to modify or delete several items at once through slice assignment. This operation can replace, remove, or even clear the entire list.

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2:5] = ['C', 'D', 'E']  # replace a range
print(letters)

letters[2:5] = []               # remove items
print(letters)

letters[:] = []                 # clear the list
print(letters)
Listing 139 — Assigning to Slices

Output

['a', 'b', 'C', 'D', 'E', 'f', 'g']
['a', 'b', 'f', 'g']
[]

Slice assignment updates several list items without a loop.

Other Useful Features

The following functions and methods help you inspect, copy, and organize lists.

Measuring Length with len()

The len() function returns the number of elements in a list.

letters = ['a', 'b', 'c', 'd']
print(len(letters))
Listing 140 — Measuring Length with len()

Output

4

Here,len(letters) returns 4 because the list has four elements.

Removing Items by Value with remove()

Sometimes the value itself is known, but not its position. The .remove() method deletes the first occurrence of the specified value from the list.

numbers = [10, 20, 30, 20]
numbers.remove(20)
print(numbers)
Listing 141 — Removing Items by Value with remove()

Output

[10, 30, 20]

Notice that only the first 20 was removed, while the second remained. This can be useful when cleaning data (e.g., removing an unwanted value from a dataset).

Removing Items by Index with pop()

If the position of the element is known,.pop() is often the better choice. It removes the item at a given index and also returns it, which can be stored in a variable.

numbers = [1, 2, 3, 4]
removed = numbers.pop(2)
print("Removed:", removed)
print("Remaining:", numbers)
Listing 142 — Removing Items by Index with pop()

Output

Removed: 3
Remaining: [1, 2, 4]

Here, the element at index 2 (the third element) was removed and stored in the variable removed. If no index is given,.pop() removes the last element.

Sorting a List with sort()

Often, lists need to be ordered — alphabetically, numerically, or even by custom rules. Python’s .sort() method rearranges the list in place.

grades = [88, 75, 92, 100, 67]
grades.sort()
print(grades)
Listing 143 — Sorting a List with sort()

Output

[67, 75, 88, 92, 100]

Here the grades are ordered from lowest to highest. The .sort() method modifies the original list instead of creating a new one. Sorting is crucial in tasks such as ranking, searching, or preparing data for analysis.

Copying Lists Safely with copy()

Assigning one list to another does not create a new copy — it creates a second name for the same list. To avoid accidental changes, the .copy() method creates a shallow copy.

colors = ["red", "blue", "green"]
new_colors = colors.copy()

new_colors.append("yellow")
print("Original:", colors)
print("Copy:", new_colors)
Listing 144 — Copying Lists Safely with copy()

Output

Original: ['red', 'blue', 'green']
Copy: ['red', 'blue', 'green', 'yellow']

Here the new list new_colors was extended, but the original colors stayed unchanged.

Nested Lists

Lists can even contain other lists. This allows us to model more complex data structures such as tables, grids, or matrices.

matrix = [[1, 2], [3, 4], [5, 6]]

print(matrix[1])     # the second row
print(matrix[1][0])  # the first element of the second row
Listing 145 — Nested Lists

Output

[3, 4]
3

The outer list has three elements, and each element is itself a list of two numbers. Accessing matrix[1][0] drills down: first into the second row, then into its first element. Nested lists are the foundation for working with 2D data, such as spreadsheets, images, or chessboards.

Mini Project — Shopping List Manager

Write a program that allows users to build and edit a shopping list interactively.

Instructions:

  • Start with an empty list.
  • Ask the user to enter three items.
  • Display the full list and the number of items.
  • Replace one item, insert another, remove one by value, and finally sort the list alphabetically.
  • Make a safe copy of the final list to confirm independence.

Example Run:

Enter an item: Milk
Enter an item: Bread
Enter an item: Apples
Your shopping list (3 items): ['Milk', 'Bread', 'Apples']

Updating list...
Replacing 'Bread' with 'Oat Bread'
Inserting 'Eggs' at the start
Removing 'Apples'
Sorted list: ['Eggs', 'Milk', 'Oat Bread']
Safe copy: ['Eggs', 'Milk', 'Oat Bread']
Original remains: ['Eggs', 'Milk', 'Oat Bread']
Listing 146 — Mini Project — Shopping List Manager

This project demonstrates how lists can store, modify, and manage data dynamically — a key concept for applications like inventories, user inputs, or data processing pipelines.