How to Sort Command-Line Arguments in Python

Build a beginner-friendly argparse CLI that sorts numbers or words passed as arguments, with an optional reverse flag.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

20 lines
Python 3.9+
import argparse


def main():
    parser = argparse.ArgumentParser(description="Sort numbers or words from the command line.")
    parser.add_argument("items", nargs="+", help="Items to sort (numbers or words)")
    parser.add_argument("--reverse", "-r", action="store_true", help="Sort in descending order")
    args = parser.parse_args()

    try:
        values = [float(item) for item in args.items]
    except ValueError:
        values = args.items

    result = sorted(values, reverse=args.reverse)
    print("Sorted:", result)


if __name__ == "__main__":
    main()

Output

stdout
$ python sort_cli.py 5 3 8 1
Sorted: [1.0, 3.0, 5.0, 8.0]

$ python sort_cli.py banana apple cherry --reverse
Sorted: ['cherry', 'banana', 'apple']

How it works

The script uses argparse to parse command-line arguments, defining items as a variadic argument with nargs="+" to accept one or more values. It attempts to convert each item to a float using a list comprehension wrapped in a try/except; if any conversion fails, it falls back to treating them as strings. The sorted() function then sorts the values, and the --reverse flag (stored as a boolean by action="store_true") controls ascending or descending order. Finally, it prints the sorted result with a clear label.

Common mistakes

  • Forgetting to include `if __name__ == "__main__":` so the script runs when executed directly
  • Assuming items are always numbers; mixing numbers and words causes the fallback to string sorting
  • Not using `nargs="+"` so the CLI requires at least one value
  • Passing the `-r` flag as `--reverse=True` instead of just `--reverse`

Variations

  1. Use `parser.add_argument('--key', default=None)` to sort by a custom key function
  2. Add `parser.add_argument('--unique', action='store_true')` to remove duplicates with `set()` before sorting

Real-world use cases

  • Sorting filenames or log lines passed to a shell script for quick inspection in a pipeline.
  • Ranking numeric metrics like test scores or throughput values from a script invocation.
  • Preprocessing unsorted user input in an interactive automation tool before further processing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.