How to pass a list as a command-line argument with Python argparse?

Sometimes, we want to pass a list as a command-line argument with Python argparse.

In this article, we’ll look at how to pass a list as a command-line argument with Python argparse.

How to pass a list as a command-line argument with Python argparse?

To pass a list as a command-line argument with Python argparse, we can use the add_argument to add the argument.

For instance, we write

parser.add_argument('-l','--list', nargs='+', help='<Required> Set flag', required=True)

to call add_argument with the argument flag’s short and long forms.

We set nargs to '+' to let us take one or more argument for the flag.

And then we set help to a string with the help text for the flag.

Conclusion

To pass a list as a command-line argument with Python argparse, we can use the add_argument to add the argument.