bhylu.com

Advertisements

List Methods

List methods fall into reading, mutation, and copying jobs. Know whether the chosen method returns information or changes the container.

Understand the idea

count reports equal occurrences; index finds the first matching position and raises ValueError when absent. reverse changes the list in place rather than sorting it. copy is shallow. append, extend, insert, remove, pop, clear, and sort each have distinct contracts that should match the operation's intent.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

labels = ["open", "closed", "open"]
print(labels.count("open"))
print(labels.index("closed"))
labels.reverse()
print(labels)

Read the result

The first results are 2 and 1. Reversing keeps the same values in opposite positional order.

Try one change

Compare reversed(labels), labels[::-1], and labels.reverse(), noting their return types and mutation.