18. Lists

A list in Python is used to store multiple items in a single variable.
Lists are ordered, changeable, and created using square brackets [].
Each item in a list is separated by a comma.
Lists can contain items of different data types, including strings, integers, floats, and even other lists.
# Creating a simple list of fruits
fruits = ["apple", "banana", "cherry"]

18.1. Adding Items to a List

To add new items to an existing list, Python gives us three primary methods:

  • .append(item): Adds a single item to the very end of the list.

  • .insert(index, item): Adds an item at a specific position (index). Remember that Python counts starting from 0.

  • .extend(iterable): Appends multiple items from another list (or iterable) to the end of the current list.

18.1.1. The .append() Method

The .append(item) method adds a single item to the very end of the list.

inventory = ["sword", "shield"]

# Adds "potion" to the end
inventory.append("potion")
print(inventory)  # Output: ["sword", "shield", "potion"]

18.1.2. The .insert() Method

The .insert(index, item) method adds an item at a specific position (index). Remember that Python uses zero-based indexing, so 0 is the first position.

inventory = ["sword", "shield", "potion"]

# Inserts "map" at index 1 (second position)
inventory.insert(1, "map")
print(inventory)  # Output: ["sword", "map", "shield", "potion"]

18.1.3. The .extend() Method

The .extend(iterable) method appends multiple items from another list (or iterable) to the end of the current list.

inventory = ["sword", "map", "shield", "potion"]
more_items = ["bow", "arrow"]

# Adds multiple items from another list to the end
inventory.extend(more_items)
print(inventory)  # Output: ["sword", "map", "shield", "potion", "bow", "arrow"]

18.1.4. Quiz: Adding Items

18.1.4.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
.append()
.extend()
.insert()
0
brackets

1. To add a single new item to the very end of a list, use the Drop here method.
2. To place an item at a specific position in a list, use the Drop here method.
3. To add all items from another list to the end of your current list, use the Drop here method.
4. Python list indices always start counting from the number Drop here.
5. Lists in Python are defined using square Drop here.

18.1.4.2. Code Ordering Examples

Example 1: Create an inventory list, add a shield to the end, and print the result.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(inventory)
☰
inventory.append("shield")
☰
inventory = ["sword"]

Example 2: Create a fruit list, insert a mango at the front (index 0), and print the list.

Drag and drop lines into the correct order and click to adjust indentation:
☰
fruits.insert(0, "mango")
☰
fruits = ["apple", "banana"]
☰
print(fruits)

Example 3: Create a list of primary colors, extend it with secondary colors, and print the total list.

Drag and drop lines into the correct order and click to adjust indentation:
☰
primary = ["red", "blue", "green"]
☰
secondary = ["yellow", "magenta", "cyan"]
☰
print(primary)
☰
primary.extend(secondary)

18.1.4.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Which method adds a single item to the very end of a Python list?

Correct! .append() adds one element to the end.

Incorrect. .insert() requires a specific index position.

Incorrect. .extend() is used to combine another list into the current list.

Incorrect. Python lists do not have an .add() method.

Where does inventory.insert(0, "map") place the string "map"?

Correct! Index 0 is the first position.

Incorrect. Index 0 refers to the first position.

Incorrect. To add to the end, use .append().

Incorrect. .insert() shifts existing items right without overwriting them.

What happens if you use .extend(["a", "b"]) on a list named letters?

Incorrect. .extend() adds all items from the passed list.

Incorrect. That would happen if you used .append([“a”, “b”]).

Correct! .extend() unwraps the list and adds each element.

Incorrect. .extend() takes an iterable like a list as its argument.

Which code block correctly adds "dragon" as the second item in a list named monsters?

Incorrect. .append() places items at the end.

Correct! Index 1 represents the second position in a list.

Incorrect. .extend() with a string will unpack every character (‘d’, ‘r’, ‘a’…) separately.

Incorrect. Index 2 represents the third position.

What is the difference between .append() and .extend() when passed a list [1, 2]?

Correct! .append() keeps nested structures while .extend() flattens them.

Incorrect. Both add to the end of the list.

Incorrect. Both work with any data type.

Incorrect. They handle list arguments differently.

What will items = ["book"]; items.extend(["pen", "ruler"]); print(len(items)) output?

Incorrect. Two new items were added.

Incorrect. The original item “book” remains in the list.

Correct! “book”, “pen”, and “ruler” make 3 items in total.

Incorrect. Exactly 2 items were added to 1 existing item.

How do you add multiple items from new_scores into an existing list all_scores?

Incorrect. .add() is not a list method.

Incorrect. .insert() requires an index argument.

Correct! .extend() combines elements from new_scores into all_scores.

Incorrect. .push() is used in JavaScript, not Python.

What bracket symbol must be used when creating a new list?

Incorrect. {} creates dictionaries or sets.

Incorrect. () creates tuples or surrounds function arguments.

Correct! Lists use square brackets [].

Incorrect. <> are comparison operators in Python.

Given nums = [10, 30], which command makes the list [10, 20, 30]?

Incorrect. .append(20) makes [10, 30, 20].

Correct! Index 1 places 20 between 10 and 30.

Incorrect. Integers are not iterable in .extend().

Incorrect. The first argument of .insert() must be the index (1), not the value (20).

What happens if you run data = [1, 2]; data.extend("34")?

Correct! Strings are iterable, so .extend() adds each character as an item.

Incorrect. .extend() iterates through the string characters.

Incorrect. Strings are valid iterables for .extend().

Incorrect. The items added are strings (‘3’, ‘4’), not integers.

Question 1 of 0

18.2. Deleting Items from a List

Python provides several ways to remove items depending on whether you know the item’s value, its position (index), or if you want to wipe the list completely.

  • .remove(item): Deletes the first matching item by value.

  • .pop(index): Removes and returns the item at a specific index. If no index is given, it removes the last item.

  • del list[index]: Deletes an item at a specific index using the del statement.

  • .clear(): Removes all items from the list, leaving it completely empty [].

18.2.1. The .remove() Method

The .remove(item) method searches for an item by its value and deletes the first matching occurrence from the list.

pets = ["dog", "cat", "fish", "cat"]

# Removes the first occurrence of "cat"
pets.remove("cat")
print(pets)  # Output: ["dog", "fish", "cat"]

18.2.2. The .pop() Method

The .pop(index) method removes and returns the item at a specific index. If no index argument is provided, it automatically removes and returns the very last item.

pets = ["dog", "fish", "cat"]

# Removes and returns the item at index 0 ("dog")
removed_pet = pets.pop(0)
print(removed_pet)  # Output: "dog"
print(pets)         # Output: ["fish", "cat"]

18.2.3. The del Statement

The del statement deletes an item at a specific index without returning its value. It can also be used to delete slices or entire variables.

pets = ["fish", "cat"]

# Deletes the item at index 1 ("cat")
del pets[1]
print(pets)  # Output: ["fish"]

18.2.4. The .clear() Method

The .clear() method removes all items from the list at once, leaving behind a completely empty list [].

pets = ["fish"]

# Wipes all remaining items from the list
pets.clear()
print(pets)  # Output: []

18.2.5. Quiz: Deleting Items

18.2.5.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
.pop()
.remove()
ValueError
del
last

1. To delete an item by value rather than position, use the Drop here method.
2. To delete and return an item by index, use the Drop here method.
3. If no argument is passed to ``.pop()``, it automatically removes the Drop here item.
4. You can use the Drop here keyword followed by ``list[index]`` to delete an item at a specific position.
5. Attempting to ``.remove()`` an item that does not exist in the list raises a Drop here.

18.2.5.2. Code Ordering Examples

Example 1: Create a list of animals, remove “dog” by value, and print the remaining list.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(animals)
☰
animals = ["cat", "dog", "bird"]
☰
animals.remove("dog")

Example 2: Create a scores list, pop the first score (index 0), and print the popped score.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(removed_score)
☰
removed_score = scores.pop(0)
☰
scores = [100, 85, 90]

Example 3: Create a list of colors, delete the middle color using del, and print the list.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(colors)
☰
colors = ["red", "green", "blue"]
☰
del colors[1]

18.2.5.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Which method removes an item by its value rather than its index?

Correct! .remove() searches for a matching value and deletes it.

Incorrect. .pop() uses index numbers.

Incorrect. del uses index brackets.

Incorrect. .clear() deletes all items in a list.

What happens when you execute nums = [10, 20, 30]; nums.pop()?

Incorrect. Without an argument, .pop() targets the last item.

Incorrect. Index 1 (20) is only removed if you pass .pop(1).

Correct! Calling .pop() with no parameters removes the last item.

Incorrect. .pop() works without parameters on non-empty lists.

If items = ["apple", "banana", "apple"], what does items.remove("apple") do?

Incorrect. .remove() only deletes the first match it finds.

Correct! .remove() stops scanning after finding and deleting the first match.

Incorrect. It searches left-to-right and deletes the first match.

Incorrect. “apple” exists in the list.

How do you delete the item at index 2 using the del keyword?

Correct! Proper syntax is del list_name[index].

Incorrect. del is a statement, not a function structured like this.

Incorrect. del is not a method attached to list objects.

Incorrect. List indices must use square brackets [].

What error occurs if you run colors = ["red"]; colors.remove("blue")?

Incorrect. IndexError occurs when an index is out of bounds.

Correct! Searching for a non-existent item in .remove() raises a ValueError.

Incorrect. Passing a string to .remove() is valid syntax.

Incorrect. NameError occurs when a variable name is not defined.

Given letters = ["a", "b", "c"], what does popped = letters.pop(1) store in popped?

Incorrect. “a” is at index 0.

Correct! .pop(1) removes and returns “b” at index 1.

Incorrect. “c” is at index 2.

Incorrect. .pop() returns the removed value.

Which statement about .pop() vs del is true?

Correct! .pop() can be assigned to a variable to save the removed item.

Incorrect. .pop() can take no arguments; del requires a target.

Incorrect. Both remove items by index.

Incorrect. Both work on lists.

What will be the value of pets after pets = ["cat", "dog"]; del pets[0]?

Incorrect. Index 0 was deleted.

Correct! “cat” at index 0 is removed, leaving [“dog”].

Incorrect. “cat” was at index 0.

Incorrect. Only index 0 was deleted, not the whole list.

What does items = [1, 2, 3]; items.pop(-1) remove?

Incorrect. Index -1 refers to the last element.

Incorrect. Index -1 targets the last position.

Correct! Negative indices count from the end; -1 is the last item.

Incorrect. Negative indexing is valid in Python.

How do you remove ALL items from a list named data so it becomes []?

Incorrect. .remove() requires an argument.

Incorrect. Invalid syntax for .pop().

Correct! .clear() removes all elements from a list.

Incorrect. del data deletes the variable entirely, not just its contents.

Question 1 of 0

18.3. Sorting and Reversing Lists

You can reorder the items inside a list using methods that modify the list in place, or use functions that create a new sorted list:

  • .sort(): Sorts the list in ascending order in place (alphabetical for text, smallest-to-largest for numbers).

  • .sort(reverse=True): Sorts the list in descending order in place.

  • sorted(iterable): Returns a new sorted list without modifying the original list. Can also take reverse=True.

  • .reverse(): Reverses the current order of elements in place without alphabetizing or numerical sorting.

18.3.1. The .sort() Method

The .sort() method reorders items in ascending order directly inside the original list (alphabetically for text, or smallest-to-largest for numbers).

scores = [45, 12, 89, 33]

# Sorts the original list in ascending order
scores.sort()
print(scores)  # Output: [12, 33, 45, 89]

18.3.2. Sorting in Descending Order (.sort(reverse=True))

Passing the parameter reverse=True into the .sort() method reorders the list in descending order (largest-to-smallest or reverse alphabetical).

scores = [12, 33, 45, 89]

# Sorts the original list in descending order
scores.sort(reverse=True)
print(scores)  # Output: [89, 45, 33, 12]

18.3.3. The sorted() Function

The sorted(iterable) built-in function returns a brand new sorted list while leaving the original list completely unchanged. It also accepts reverse=True.

numbers = [5, 2, 8, 1]

# Creates a new sorted list without modifying the original
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 2, 5, 8]
print(numbers)         # Output: [5, 2, 8, 1]

18.3.4. The .reverse() Method

The .reverse() method simply flips the current order of elements in place without performing any alphabetical or numerical sorting.

colors = ["red", "blue", "green"]

# Reverses the element positions in place
colors.reverse()
print(colors)  # Output: ["green", "blue", "red"]

18.3.5. Quiz: Sorting and Reversing

18.3.5.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
.reverse()
.sort()
place
reverse=True
smallest

1. To arrange items in ascending or alphabetical order, call the Drop here method.
2. To sort a list in descending order, pass Drop here into the ``.sort()`` method.
3. To flip the order of items without sorting them numerically or alphabetically, use the Drop here method.
4. By default, calling ``.sort()`` on numbers orders them from Drop here to largest.
5. Both ``.sort()`` and ``.reverse()`` modify the original list in Drop here rather than returning a new list.

18.3.5.2. Code Ordering Examples

Example 1: Create a list of unsorted numbers, sort them in ascending order, and print the result.

Drag and drop lines into the correct order and click to adjust indentation:
☰
numbers = [42, 11, 88, 23]
☰
print(numbers)
☰
numbers.sort()

Example 2: Create a list of names, sort them in reverse alphabetical order, and print them.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(names)
☰
names.sort(reverse=True)
☰
names = ["Charlie", "Alice", "Bob"]

Example 3: Create a list of steps, reverse their order, and print the reversed steps.

Drag and drop lines into the correct order and click to adjust indentation:
☰
steps.reverse()
☰
print(steps)
☰
steps = ["Step 1", "Step 2", "Step 3"]

18.3.5.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What does calling .sort() on a list of strings do by default?

Correct! Default sorting for strings is alphabetical.

Incorrect. Reverse sorting requires reverse=True.

Incorrect. Default sort handles lexicographical order.

Incorrect. Flipping without sorting is done by .reverse().

What is the result of nums = [3, 1, 4]; nums.sort()?

Incorrect. .sort() modifies the list.

Correct! .sort() orders numbers from smallest to largest.

Incorrect. Smallest to largest is default.

Incorrect. Numbers are ordered sequentially.

How do you sort a list of numbers from highest to lowest?

Incorrect. The parameter name is reverse, not descending.

Correct! Setting reverse=True sorts in descending order.

Incorrect. .reverse() does not take a sort argument.

Incorrect. No such method exists in Python.

Given items = ["a", "c", "b"], what does items.reverse() produce?

Incorrect. .reverse() does not sort alphabetically.

Correct! It flips the current list order directly.

Incorrect. That would be alphabetical reverse sort.

Incorrect. It flips end-to-end.

What value is returned when you assign x = my_list.sort()?

Incorrect. .sort() modifies in place and returns None.

Correct! Methods that modify lists in place return None.

Incorrect. It returns None.

Incorrect. It returns None.

What happens if you try to run .sort() on a list containing both numbers and strings like [1, "apple", 2]?

Incorrect. Python 3 cannot compare strings and integers directly.

Incorrect. Mixed type sorting is not supported automatically.

Correct! Comparing str and int raises a TypeError during sorting.

Incorrect. An exception is thrown.

Which method flips a list’s elements end-to-end without comparing their values?

Incorrect. .sort() compares values.

Incorrect. .extend() adds elements.

Correct! .reverse() simply reverses index order.

Incorrect. .pop() deletes elements.

What will vals = [10, 5, 20]; vals.sort(); vals.reverse(); print(vals) output?

Incorrect. Sorting then reversing gives descending order.

Correct! Sorting gives [5, 10, 20], and reversing gives [20, 10, 5].

Incorrect. The methods alter the list.

Incorrect. Reversing [5, 10, 20] gives [20, 10, 5].

If words = ["banana", "apple", "cherry"], what is words after words.sort()?

Correct! Alphabetical order.

Incorrect. Reverse alphabetical.

Incorrect. List is modified.

Incorrect. Incorrect alphabetical order.

How does built-in function sorted(my_list) differ from method my_list.sort()?

Correct! sorted() leaves the original list untouched.

Incorrect. Both work on both types.

Incorrect. It is the opposite.

Incorrect. Their return values and side effects differ.

Question 1 of 0

18.4. Iterating Through a List

Iterating means going through items in a list one by one. We use a for loop to do this efficiently.

team = ["Alex", "Sam", "Jordan"]

# Loop through each item in the list
for player in team:
    print(f"Welcome to the team, {player}!")

# Output:
# Welcome to the team, Alex!
# Welcome to the team, Sam!
# Welcome to the team, Jordan!

18.4.1. Quiz: Iterating Through Lists

18.4.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
colon
for
indentation
len()
variable

1. To step through each item in a list one by one, use a Drop here loop.
2. The word following ``for`` in a loop serves as a loop Drop here holding the current item.
3. The header line of a ``for`` loop must end with a Drop here.
4. Code inside the loop block must use four spaces of Drop here to run properly.
5. The built-in function Drop here can be used to find the total number of iterations a loop over a list will make.

18.4.1.2. Code Ordering Examples

Example 1: Create a list of fruits and use a for loop to print each fruit.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(fruit)
☰
for fruit in fruits:
☰
fruits = ["apple", "banana", "cherry"]

Example 2: Create a list of numbers, calculate their double in a loop, and print each doubled value.

Drag and drop lines into the correct order and click to adjust indentation:
☰
for n in numbers:
☰
print(double_val)
☰
numbers = [1, 2, 3]
☰
double_val = n * 2

Example 3: Create a list of names, check if each name is “Alice”, and print a greeting when matched.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print("Hello Alice!")
☰
names = ["Alice", "Bob"]
☰
if name == "Alice":
☰
for name in names:

18.4.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Which keyword starts a loop that iterates over items in a list?

Correct! Python uses for loops to iterate over sequences.

Incorrect. loop is not a Python keyword.

Incorrect. foreach is used in languages like PHP or C#.

Incorrect. repeat is not a Python keyword.

How many times will the print statement execute in for x in [10, 20, 30, 40]: print(x)?

Incorrect. There are 4 items in the list.

Correct! The loop runs once for each item in the list.

Incorrect. The loop visits only items in the list.

Incorrect. The loop iterates over all items.

What character MUST end the first line of a for loop statement?

Incorrect. Python uses colons for block headers.

Correct! Compound statements in Python end header lines with a colon.

Incorrect. Python does not use periods for headers.

Incorrect. Commas separate items, not header blocks.

In for item in inventory:, what does item represent?

Incorrect. item represents one element at a time.

Correct! It temporarily stores the active element during that loop step.

Incorrect. It holds the actual value, not the index.

Incorrect. It is an iteration variable.

What error occurs if you forget to indent code inside a for loop body?

Correct! Python requires indented blocks after colons.

Incorrect. Specifically, Python raises IndentationError.

Incorrect. Missing indentation causes an IndentationError.

Incorrect. Indentation governs block structures.

Which function can be combined with range() to loop using index numbers?

Incorrect.

Correct! range(len(my_list)) generates index positions 0 to len-1.

Incorrect.

Incorrect.

What will for c in ["a", "b"]: print(c, end="") print?

Incorrect. end=”” prevents newlines.

Correct! It prints “a” and “b” continuously on one line.

Incorrect. The loop prints elements individually.

Incorrect. No space separator was specified.

Question 1 of 0