bhylu.com

Advertisements

Python List Methods

List methods either inspect a sequence or change the existing object. Their return values are part of the method contract.

Understand the idea

append, extend, insert, remove, clear, reverse, and sort mutate in place and normally return None. pop returns the removed item. count and index inspect values. copy duplicates the outer container only. The table below is a compact reminder; the main lessons explain examples and aliasing in more detail.

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

values = [3, 1, 3]
removed = values.pop()
values.sort()
print(removed, values)

Read the result

The removed value is 3 and the remaining sorted list is [1, 3].

Try one change

Write a non-mutating sorted copy and prove that the original order remains unchanged.

Quick lookup

OperationMeaning and limit
append / extend / insertMutate by adding one object, an iterable's elements, or one positioned object.
remove / pop / clearDelete a first matching value, return a removed position, or empty the list.
index / countFind a first equal position or count equal occurrences.
sort / reverseMutate ordering; both return None.
copyMake a shallow outer copy.
sorted / reversed / enumerateBuilt-ins producing a new list, a reverse iterator, or counted pairs; they are not list methods.