Split a CSV string into a list of row lists by breaking on newlines and then on commas. The replay shows rows growing one split row at a time, with the header row appearing as the first element.

By hand

The Pythonic way

csv.reader wraps an io.StringIO text stream and handles splitting automatically. list(reader) materialises all rows at once.

naive.py
csv_text = 'id,cat,val\n1,x,10\n2,y,20\n3,x,30'
lines = csv_text.split('\n')
rows = []
for line in lines:
    rows.append(line.split(','))
print('RESULT:', (len(rows), rows[-1]))
library.py
import csv
import io
csv_text = 'id,cat,val\n1,x,10\n2,y,20\n3,x,30'
rows = list(csv.reader(io.StringIO(csv_text)))
print('RESULT:', (len(rows), rows[-1]))
RESULT: (4, ['3', 'x', '30'])

Implementation notes

  • RESULT prints (row_count, last_row) — the full list of 4 rows would exceed the 80-char trace limit, so only the count and last row are shown.
  • .split(',') breaks on every comma, including commas inside quoted fields; csv.reader handles quoting correctly. For simple numeric data without embedded commas the manual split is equivalent.
  • See csv-to-dicts (this chapter) for the next step: mapping each row to a dict using the header row.