argparse
command-line arguments
Python
programming tutorial
list manipulation

How can I pass a list as a command-line argument with argparse?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Passing a list to Python CLI tools with argparse is a common need for batch IDs, feature names, and repeated options. There are several valid patterns, each with tradeoffs in UX and parsing complexity. The cleanest approach is usually repeated arguments (nargs or repeated flag usage), while comma-separated strings can work when shell ergonomics matter. Choosing one format and documenting it clearly prevents ambiguity in scripts and automation.

Core Sections

Use nargs for space-separated list input

nargs='+' captures one or more values.

python
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument("--ids", nargs="+", type=int, required=True)
5args = parser.parse_args()
6print(args.ids)

Usage:

bash
python app.py --ids 10 20 30

This is explicit and easy to validate.

Use repeated flags with action='append'

Useful when values are provided across contexts.

python
parser.add_argument("--tag", action="append", default=[])

Usage:

bash
python app.py --tag blue --tag green --tag red

Result is a list in insertion order.

Parse comma-separated lists

If your CLI needs a single argument token:

python
1def csv_list(value):
2    return [x.strip() for x in value.split(",") if x.strip()]
3
4parser.add_argument("--names", type=csv_list)

Usage:

bash
python app.py --names "alice,bob,charlie"

Be clear about escaping/quoting when values may contain commas.

Type conversion and validation

Combine list parsing with validators.

python
1def positive_int(v):
2    iv = int(v)
3    if iv <= 0:
4        raise argparse.ArgumentTypeError("must be positive")
5    return iv
6
7parser.add_argument("--ports", nargs="+", type=positive_int)

Validation at parse time gives better UX than later runtime errors.

Output schema consistency

Keep parsed list format consistent across command versions. Changing input style without backward compatibility can break scripts.

Common Pitfalls

  • Mixing list input styles across commands and confusing users.
  • Using comma-separated parsing without handling spaces and empty tokens.
  • Forgetting shell quoting when list elements include special characters.
  • Performing list validation only after parsing and producing unclear errors.
  • Breaking automation by changing CLI list semantics without migration notes.

Verification Workflow

Add CLI tests for each supported list format, including invalid inputs and empty values. Validate behavior in bash, zsh, and CI shells used by your team. Keep --help examples synchronized with parser behavior to reduce support friction.

text
11. Test nargs-based input
22. Test repeated-flag input
33. Test invalid tokens and type errors
44. Test shell quoting edge cases
55. Verify help text examples

Production Readiness Checklist

Before considering the implementation complete, run a repeatable readiness pass that validates correctness, failure handling, and operational behavior in the same environment class where this solution will run. Start with a deterministic happy-path example and then exercise one malformed input and one resource-constrained scenario. Capture structured output such as status codes, key counters, and timing metrics so regressions are visible across revisions.

Document expected behavior boundaries in plain language so future maintainers can quickly understand what is guaranteed and what is best-effort. If configuration affects behavior, include the exact setting names and safe defaults in your runbook. For team workflows, add one lightweight automated check in CI to enforce these expectations on every change and keep debugging effort low when dependencies or runtime versions change.

text
11. Validate normal input path
22. Validate malformed or missing input path
33. Validate constrained-resource behavior
44. Record timing and error metrics
55. Confirm rollback or fallback behavior
66. Add CI smoke check for regression detection

Practical Deployment Note

When adopting this approach in team environments, apply changes incrementally and validate each step with one deterministic sample before broad rollout. Incremental validation shortens debugging cycles, reduces rollback scope, and helps isolate compatibility issues tied to runtime versions, environment settings, or dependency changes. Preserve one known-good baseline configuration so you can compare behavior quickly when outputs diverge from expected results after future updates.

Summary

argparse supports list arguments cleanly via nargs, repeated flags, or custom parsers. Choose one style intentionally, enforce validation at parse time, and document usage clearly. Consistent list parsing makes CLI tools easier to automate and maintain.


Course illustration
Course illustration

All Rights Reserved.