liveBook · Manning

Reversing

As explained in Python How-To

The reverse method is a Python list method that reverses a list in place and returns None.

Use the reverse method when a list itself should change order. It reverses the original list in place and returns None, so assign no result and do not pass the call directly to a for loop. section 5.3.6

Reverse the list before using it

tasks = ["task1", "task2", "task3"] tasks.reverse() print(tasks) # ['task3', 'task2', 'task1'] section 4.1.1 section 5.3.6

Choose the operation according to whether the original list should change:

  • Use reverse() when in-place mutation is intended. section 4.1.1
  • Use reversed(tasks) when iterating backward while preserving the original list. section 5.3.2
  • Avoid confusing reverse() with reversed(), just as sort() differs from sorted(). section 5.3.6
  • Prefer reverse() followed by ordinary left-to-right slicing when negative-step slicing would reduce readability. section 4.1.1
tasks = ["task1", "task2", "task3"]
for task in tasks.reverse():
   pass

Inspect the failing pattern to see why reverse() cannot supply items directly to a for loop: the method returns None after mutating the list. section 5.3.6

How Python How-To covers it

How deep it goes
Defines in-place mutation and the None return, then contrasts reverse() with reversed() and negative-step slicing.
Examples
Demonstrates reversing before slicing and contrasts it with iterating through reversed(tasks).
What it assumes
Assumes basic list operations and slicing, while clarifying the difference between mutation and reverse-order iteration.
What you can do after
Apply it to reverse an existing list in place and avoid treating its None return as reversed data.
How it connects
Connects reversing with list slicing, iterators, for loops, and the distinction between sort() and sorted().

Also explained in

Compare how 3 books explain reversing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.