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 ofval.append(val): Addsvalto the end of the list. Modifies in-place, returnsNone.insert(idx, val): Addsvalat a specificidx.remove(val): Deletes the first occurrence ofval.sort(): Sorts in-place. Tactical Detail: Uses “ASCIIbetical” order (Uppercase comes before lowercase). Usekey=str.lowerfor true alphabetical sort.
- List Operators:
+(Concatenation): Joins two lists into a new one.*(Replication): Repeats a list a specific number of times.
inandnot 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)