Editing and Ordering Lists

Introduction: Editing What Is Already There

Welcome back to Building and Modifying Lists in Python. Now that we can grow and shrink lists on command, notice what we have not done yet: changed an item that was already in the list. We added new items, removed existing ones, and changed the list’s length, but the values already stored at each position stayed the same.

This lesson covers the next part of list mutability: replacing existing values and changing a list’s order. We will use index assignment to replace one item, slice assignment to replace several items, and three ordering tools: sort(), sorted(), and reverse().

By the end of the lesson, you will know when a tool changes a list in place and when it creates a new list instead.

Replacing a Single Item by Index

Start with a small list of prices:

Python
prices = [19.99, 4.50, 12.00, 8.75]

The first price is incorrect. Because lists are mutable, we can replace that one value without rebuilding the whole list:

Python
# Lists are mutable, so an element can be replaced
prices[0] = 21.99

print("Updated prices:", prices)

An index on the right side of = reads a value from a list. The same index on the left side writes a new value into that position.

Two details matter:

  • The list’s length does not change. One value is replaced by one new value.
  • The index must already exist. For example, prices[10] = 5.0 raises an IndexError because index assignment cannot create a new position.

Negative indices work here too. For example, prices[-1] = 9.00 would replace the final item.

text
Updated prices: [21.99, 4.5, 12.0, 8.75]

Replacing a Range with Slice Assignment

We can also replace several neighboring items in one statement. A slice on the left side of = selects the range to replace:

Python
# A range of elements can be replaced with slice assignment
prices[1:3] = [5.00, 13.50]

print("Updated prices:", prices)

The slice prices[1:3] includes indices 1 and 2 but excludes index 3. The old prices at those positions are replaced by the two new prices.

Slice assignment replacing values at indices 1 and 2

The diagram shows that the selected middle range is replaced while the first and final values remain in place. After the replacement, the list contains these updated prices:

text
Updated prices: [21.99, 5.0, 13.5, 8.75]

The replacement list does not have to be the same length as the slice:

Python
letters = ["a", "b", "c", "d"]

letters[1:3] = ["x"]
print(letters)

letters[1:2] = []
print(letters)

The first assignment replaces two items with one, so the list shrinks. The second assignment replaces one item with an empty list, which deletes that item.

text
['a', 'x', 'd']
['a', 'd']

Sorting in Place with sort()

Once the prices are correct, we can arrange them from smallest to largest with sort():

Python
# sort() changes the existing list in place
prices.sort()

print("Sorted ascending:", prices)

The sort() method changes the original list directly and returns None, which is why we print prices after sorting instead of storing what sort() hands back:

text
Sorted ascending: [5.0, 8.75, 13.5, 21.99]

That return value is worth one more moment. Avoid this common mistake:

Python
prices = prices.sort()

After that line, prices would hold None rather than the sorted list.

Sorting Descending with reverse=True

By default, sort() orders items from smallest to largest. Add reverse=True to sort from largest to smallest instead:

Python
prices.sort(reverse=True)

print("Sorted descending:", prices)

This is still a full sort, not just a simple flip of the current order. Python compares the values and places them in descending order.

text
Sorted descending: [21.99, 13.5, 8.75, 5.0]

Sorting a Copy with sorted()

Sometimes we want a sorted version while keeping the original order unchanged. In that case, use sorted():

Python
names = ["Zoe", "Ada", "Max"]

# sorted() returns a new list and preserves the original
sorted_names = sorted(names)

print("Sorted copy:", sorted_names)
print("Original:", names)

Unlike sort(), sorted() is a built-in function rather than a list method. It creates and returns a new list, so storing its result is the correct approach.

The original names list stays in the order in which it was created:

text
Sorted copy: ['Ada', 'Max', 'Zoe']
Original: ['Zoe', 'Ada', 'Max']

Use sort() when the old order no longer matters. Use sorted() when you need both the original and ordered versions.

Flipping Order with reverse()

The reverse() method flips the current order of a list from end to end:

Python
# reverse() flips the current order in place
names.reverse()

print("Reversed original:", names)

This method does not sort alphabetically. It simply makes the last item first and the first item last.

Because names originally held ["Zoe", "Ada", "Max"], reversing it produces this order:

text
Reversed original: ['Max', 'Ada', 'Zoe']

The following comparison helps separate the three related tools:

ToolSorts items?Changes the original list?Result
list.reverse()No, it flips the current orderYesReturns None
list.sort(reverse=True)Yes, descendingYesReturns None
sorted(list)Yes, ascending by defaultNoReturns a new list

The key question is whether you need to preserve the original list. If you do, use sorted(); otherwise, sort() and reverse() update the list you already have.

Bringing It Together

The complete example below replaces prices, sorts them in both directions, creates a sorted copy of a name list, and reverses the original name list:

Python
prices = [19.99, 4.50, 12.00, 8.75]

# Replace one item and then replace a range
prices[0] = 21.99
prices[1:3] = [5.00, 13.50]
print("Updated prices:", prices)

# Sort the existing list in both directions
prices.sort()
print("Sorted ascending:", prices)

prices.sort(reverse=True)
print("Sorted descending:", prices)

# Create a sorted copy while preserving the original
names = ["Zoe", "Ada", "Max"]
sorted_names = sorted(names)

print("Sorted copy:", sorted_names)
print("Original:", names)

# Reverse the original list in place
names.reverse()
print("Reversed original:", names)

This program produces the following output, showing which tools preserve an original list and which tools change it directly:

text
Updated prices: [21.99, 5.0, 13.5, 8.75]
Sorted ascending: [5.0, 8.75, 13.5, 21.99]
Sorted descending: [21.99, 13.5, 8.75, 5.0]
Sorted copy: ['Ada', 'Max', 'Zoe']
Original: ['Zoe', 'Ada', 'Max']
Reversed original: ['Max', 'Ada', 'Zoe']

Conclusion and Next Steps

In this lesson, you learned how to replace one list item with index assignment and several items with slice assignment. You also learned how to sort an existing list with sort(), create a separately sorted list with sorted(), and flip a list’s current order with reverse().

The most important distinction is whether an operation changes the existing list or returns a new one. Index assignment, slice assignment, sort(), and reverse() all edit a list in place. In contrast, sorted() creates a new list and leaves the original untouched.

Next, you will complete hands-on practices that correct prices, update a range of values, sort lists in both directions, and compare a sorted copy with a reversed original.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal