COGNITION FOUNDRYLEARN. BUILD. UNDERSTAND.
PY-011 / Collect related values◷ 20 min read + practice

Lists and indexes

A list holds several values in a defined order. This is more convenient than creating a separate name for every item, and it lets loops operate on all your data in a consistent way.

By the end, you can: Use indexing, slicing, append, len and iteration to work with a changing list.
Before this lesson: PY-009 · PY-010

Create an ordered collection

Square brackets create a list: tasks = ["read", "test", "share"]. Lists can store items of different types, though keeping related kinds of values together usually makes code easier to understand.

Positions start at zero. The first element is tasks[0], not tasks[1]. tasks[-1] accesses the final item; using an index outside the valid range raises IndexError.

Slices choose a section

tasks[1:3] returns a new list containing indexes 1 and 2. Like range, the stop boundary is excluded. Omitting the start or stop lets you choose from the beginning or through the end.

tasks[:2] gets the first two entries and tasks[2:] gets everything starting at index 2. Slices that extend beyond the end usually return the available portion rather than raising IndexError.

Lists can change

Lists are mutable: append() adds an item to the end and assignment such as tasks[0] = "plan" replaces an existing item. len(tasks) reports the current number of items.

Changes to a list persist while your program holds that list. This is different from strings, which cannot have individual characters replaced in place. Later we will discuss copies and references.

Loop over the items, not the indexes, when possible

for task in tasks: expresses the intent directly. If you need both the position and value, enumerate(tasks, start=1) supplies them without manually maintaining a counter.

Be cautious when removing items from the list you are iterating over, because the positions shift. For now, collect results into a new list instead of changing the structure mid-loop.

Try it yourself.

Choose a starting example or write something completely different. You control the code; the Run button executes what is in the editor, not a hidden preset.

CF Python PlaygroundBrowser-based Python
Ready to load Python
Read by position

Access the first and last items of an ordered collection.

Syntax colours highlight Python code. Tab inserts four spaces; press Escape then Tab to leave the editor. Ctrl+Enter runs the current code.
OUTPUT / ERRORS
Press Run Python to execute the editable code.
NOW MAKE IT YOURS

Add a fourth task and check whether the final index still works.

Need a hint?

Negative index -1 always refers to the last element.

On first Run, a pinned Python runtime downloads from jsDelivr. Code executes locally in your browser's Web Worker, not on our server. It cannot inspect your normal PC files or Windows hardware. Avoid entering secrets. Heavy/infinite loops are stopped by a time limit.

Check your understanding.

Try answering each question before opening its reference answer. Explain the idea aloud or change an example to test it for yourself.

  1. Why does items[3] fail for a list containing exactly three items?

    View answer

    A list with three items has valid positive indexes 0, 1 and 2. items[3] requests a fourth item, so Python raises IndexError. Use len(items) to check the size; when iterating over all elements prefer for item in items to manual index calculations.

  2. What is the difference between items[1:3] and items[1]?

    View answer

    items[1] reads the single element at index 1. items[1:3] creates a new list containing the elements at indexes 1 and 2; index 3 is excluded. The first result is an individual element while the second result is a list, even if the slice contains only one item.

Where this leads.

Lists retrieve items by numeric position. Dictionaries retrieve values by a meaningful key.