Andromeda
Note

Lists (Python)

Definition

A collection of items in a particular order. In Python, lists are dynamic, mutable, and defined using square brackets [].

Why It Matters

Lists are the most fundamental data structure for managing ordered information; a lack of mastery over list operations leads to inefficient, ‘clunky’ code that struggles to handle even basic collections of data.

Core Concepts

  • Ordered Sequence: Lists maintain a specific order. They can contain any data type, including other lists (nesting).
  • List Methods: Functions tied specifically to list values:
    • index(val): Returns the index of the first occurrence of val.
    • append(val): Adds val to the end of the list. Modifies in-place, returns None.
    • insert(idx, val): Adds val at a specific idx.
    • remove(val): Deletes the first occurrence of val.
    • sort(): Sorts in-place. Tactical Detail: Uses “ASCIIbetical” order (Uppercase comes before lowercase). Use key=str.lower for true alphabetical sort.
  • List Operators:
    • + (Concatenation): Joins two lists into a new one.
    • * (Replication): Repeats a list a specific number of times.
  • in and not in: Boolean operators used to check for existence within the list.
  • Multiple Assignment: Also known as Unpacking (e.g., cat, bat, rat = my_list), where the number of variables must match the list length.
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits.insert(1, "apricot")
fruits.remove("banana")
fruits.sort()

for fruit in fruits:
    print(fruit)

Connected Concepts