Data Engineering Lab

Python List Creation & Indexing — ordered sequences for ETL and APIs

Overview

A list is Python’s default ordered, mutable sequence: one object that holds references to other objects in insertion order. In data work you use lists for column name lists, pipeline stage names, batch keys, sensor readings, and anything you will iterate, sort, or index on the driver before handing work to Spark or SQL.

The Practice Lab (Data Fluency > Collections, ex-1-4-1a–1e) trains: 0-based access for “2nd / 4th” elements (Q1), first / last with [0] and [-1] (Q2), creating and inspecting a mixed-type list with len() and in (Q3), negative indexing plus len() (Q4), and in / .index() for membership and first position (Q5).

Use the flow diagram for the index rail (positives, negatives, highlights). Open the practice map for Q1–Q5 with lab-shaped code and exact autograder output.

Enable JavaScript to explore the interactive diagram.

Map to Practice Lab questions

Lab QSkill
Q1employees[1], employees[3] → Bob then Diana (2nd / 4th in 0-based terms)
Q2temps[0], temps[-1] → 23.5 then 23.9
Q3record = ["Alice", 30, 72.5, True]; len(record) → 4; 30 in record → True
Q4scores[-2] → 79; len(scores) → 6
Q5"transform" in pipeline → True; pipeline.index("load") → 2

Practice here: Practice Lab (same topic).

Enable JavaScript to explore the interactive diagram.

Vocabulary

TermMeaning
SequenceOrdered collection — list, tuple, str; supports indexing and often slicing
0-based indexFirst element is [0]; nth element (counting from 1) is [n-1]
Negative index[-1] last, [-2] second-to-last; [-k] ≡ [len(seq)-k] when k ≤ len
len(seq)Number of elements — O(1) for lists
inMembership test — linear scan for lists, short-circuits on first match
.index(x)Index of first occurrence of x — ValueError if missing

Industry norms

PracticeWhy
Prefer [-1] over [len(x)-1] for “last”Survives append/pop without editing the index expression
Guard before .index()if x in lst: then lst.index(x) avoids ValueError in production paths
Keep “column lists” as ordered listsSchema-driven select(*cols) builders rely on deterministic order
Do not treat Spark rows as listsRow supports index and name access but lives in the JVM boundary — use collect() only for tiny samples

Examples

Example 1 — Q1 pattern: human “2nd / 4th” vs indices 1 and 3

employees = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
print(employees[1])
print(employees[3])

Output:

Bob
Diana

Example 2 — Q2 pattern: first and last in one line of thinking

temps = [23.5, 24.1, 22.8, 25.3, 23.9]
print(temps[0])
print(temps[-1])

Output:

23.5
23.9

Example 3 — Q3 pattern: create and inspect a mixed-type list

record = ["Alice", 30, 72.5, True]
print(len(record))
print(30 in record)

Output:

4
True

Example 4 — Q4 pattern: from-the-end without hard-coding length

scores = [88, 72, 95, 61, 79, 84]
print(scores[-2])
print(len(scores))

Output:

79
6

Example 5 — Q5 pattern: membership vs position

pipeline = ["extract", "transform", "load", "validate"]
print("transform" in pipeline)
print(pipeline.index("load"))

Output:

True
2

Example 6 — Building lists the way services do (literals, casts, copies)

# Literal — most common
cols = ["event_id", "user_id", "ts"]

# From any iterable (dedupe order not preserved — use sorted(set(...)) if needed)
from_csv_header = "a,b,c".split(",")

# Shallow copy when you must mutate without touching the source
base = [1, 2, 3]
working = list(base)
working.append(4)

Mistakes

Mistake 1 — 1-based mental model on lists

Wrong: “2nd employee” → employees[2] (that is Charlie, not Bob).

Correct: employees[1] for the 2nd item; ordinality - 1.


Mistake 2 — Calling .index() when the value might be absent

Wrong:

i = items.index(maybe_missing)  # ValueError if not found

Correct:

if maybe_missing in items:
    i = items.index(maybe_missing)

For repeated lookups, a dict mapping value → index (or enumerate once) beats many linear scans.


Mistake 3 — Confusing list type with list() constructor call

Wrong: a = list (binds the class, not an instance).

Correct: a = [] or a = list().


Mistake 4 — Using list.find

Wrong: [1, 2, 3].find(2) — lists have no .find() (that is for str).

Correct: 2 in lst, lst.index(2), or search patterns with enumerate.


Interview

Q1. Why is list indexing O(1)?

CPython lists are dynamic arrays of pointers; lst[i] computes an address from base + i (with bounds check). Size does not change the cost of one random access.

Q2. Difference between in and .index()?

in returns bool and stops early on match. .index(x) returns int position or raises ValueError. Both are O(n) worst case for general lists.

Q3. Are lists thread-safe?

No. Concurrent append / pop from multiple threads without locks can corrupt internal state. Use queues, locks, or process boundaries.

Q4. List vs tuple?

List — mutable, [], not hashable. Tuple — immutable, (), hashable if all elements are hashable (usable as dict keys). Use tuples for fixed records; lists for growing buffers.

Q5. How does this relate to PySpark Row?

Row supports index and name access like a narrow sequence, but rows live in the distributed layer. Driver lists are for metadata and small control data; big tables stay in DataFrames.


Python vs PySpark

Python lists are in-memory, ordered, and indexed on the driver. PySpark DataFrames expose row previews (first, head, take) and columns as a name list — same mental model for “position and name,” different scale and execution. The comparison table is generated for this topic. Use Try Now for Python and PySpark practice.


Python vs SQL

SQL result rows have no stable “first row” without ORDER BY; ordinal positions in the standard are often 1-based (SUBSTRING …). Python lists are always 0-based and explicitly ordered in memory. The comparison table is generated for this topic. Use Try Now for Python and SQL practice.