How can I pass a list as a command-line argument with argparse?
To pass a list of items to a script, leverage argparse with nargs='*'. This will collect all the values into a list. Here's how:
You can now use it like so:
python script.py --items apple banana cherry
This will render args.items as, surprise surprise, ['apple', 'banana', 'cherry'].
Argument list depth: diving deeper
Exact list size: no more, no less
Want to play bouncer with your list elements? Use nargs='+' or nargs=3 to mandate at least one or exactly three elements like some super exclusive club.
Now only three integers can join the list party.
Invoking JSON: for when lists get complex
With complex list structures, input a JSON string and then call json.loads to parse it like a boss:
Use it as such:
python script.py --data '["first", {"second": "yes, I know it is weird"}]'
List arguments: from zero to hero
To give a default value to your list argument, assign the default parameter:
Mopping up the leftovers
Want to capture all remaining arguments after a designated point? Use argparse.REMAINDER like a hoover for loose arguments:
Now everything in your command call after the first recognized flag will be gathered, no man left behind.
Building a better mousetrap: robust argument handling
Fancy input parsing: split personalities welcome
Got a string with a delimiter you want to split up? Use a custom type for a smoother ride:
Call it as so:
python script.py --coords "10,20" "30,40"
Playing safe with given choices
Your list only takes predefined values? Use choices to restrict and authenticate input, like bouncer 2.0:
Making friends with negative numbers
When handling numeric values that may be negative, use this tip:
By using --, you signal the end of options and negative numbers won't be mistaken as flags. Real problem solver, this one.
Special case handling: a guide
Repeat after me: append action
Want to use the same argument more than once? Use action='append':
Use it on repeat:
python script.py --tag DJ --tag Python
List elements' dress code: integers only
Want to ensure that your list contains elements of a specific type, say integers? Use type=int to enforce a strict dress code:
Mixing it up: options and positional arguments
Mixing positional arguments and options in a command call can get tricky. Always specify nargs to avoid a cocktail of confusion and parsing errors.
Was this article helpful?