liveBook · Manning

List

As explained in Python Workout, Second Edition

A list is a mutable ordered collection in Python.

A list is a mutable, ordered Python collection for storing, searching, extending, modifying, sorting, and replacing values. Use it naturally for sequences of related items, such as users, documents, or IP addresses. section 4.0

When working with a list, remember these practical distinctions:

  • Retrieve an individual element with an index such as values[0] or values[-1]; retrieve a sub-list with a slice such as values[2:5]. section 4.3
  • A single index can return any element type, while a list slice always returns another list; slices also tolerate boundaries beyond the list. section 4.3
  • Build accumulated output with list.append and convert it afterward with str.join instead of repeatedly concatenating immutable strings. section 3.7
  • Choose a list for a mutable sequence of related values; choose a tuple for an immutable record containing different kinds of values. section 4.0
  • Use a comprehension when the purpose of the loop is to transform an iterable into a new list; use a for loop for side effects. section 8.2

Accumulate transformed characters

For a character-by-character transformation, create an empty output list, append either the transformed character or the original character, then join the completed list with ''. This prevents the loop from repeatedly rebuilding a string and avoids reprocessing newly inserted characters. section 3.11 section 3.7

Table 4.1 Sequence comparison
Type
Mutable?
Contains
Syntax
Retrieval
str
No
One-element strings
s = 'abc'
s[0] (Returns 'a')
list
Yes
Any Python type
mylist = [10, 20, 30, 40, 50]
mylist[2] (Returns 30)
tuple
No
Any Python type
t = (100, 200, 300, 400, 500)
t[3] (Returns 400)

Compare strings, lists, and tuples by mutability, contents, syntax, and indexed retrieval. section 4.0

How Python Workout, Second Edition covers it

How deep it goes
Explains mutation, sequence retrieval, slicing, accumulation, sorting, and comprehensions, stopping short of implementation internals.
Examples
Demonstrates character translation, accumulated Pig Latin output, sliced sequences, comprehensions, and object attributes containing Scoop instances.
What you can do after
Apply lists via indexing, slicing, append, join, sorting, and comprehensions in practical Python transformations.
How it connects
Connects lists with tuples, strings, dictionaries, sets, sequences, comprehensions, and str.join.

Also explained in

Compare how 21 books explain list →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.