Python List

A Python list is an ordered, mutable collection written in square brackets: ["apple", "banana"]. It is a sequence, so it supports positions counted from 0, negative positions, slices, len(), and the in test. Unlike a string, a list can hold values of any type, including other lists, and it can be modified after creation.

Four methods cover most edits. append(value) adds one value at the end. insert(index, value) places a value at a position and shifts the rest right. remove(value) deletes the first occurrence of a value. pop(index) removes the value at a position and returns it, defaulting to the last. Assigning to a position, items[0] = "new", replaces one value; sort() and reverse() reorder the list in place and return None, while sorted() returns a new list.

The two removal methods fail in different ways, which matters inside a cleaning loop. remove() raises ValueError when the value is not present, and pop() raises IndexError when the position does not exist. Reading a position outside the list also raises IndexError, while a slice is clamped and simply returns what exists.

Two names can refer to the same list; because the list is mutable, either name can be used to change that shared object. list(original), original.copy(), and original[:] each make an independent list, though all three are shallow: inner lists remain shared. Built-in lists are unhashable, so they cannot be dictionary keys or set elements; mutability and hashability are separate concepts. Prefer a tuple when positions represent fixed fields, and prefer a dictionary when lookups are by key rather than by position.

References: Python lists, More on lists. See it in use in Python Collections and Comprehensions.


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.