function_that_needs_strings(*my_list) # works!

You can read all about it here: Unpacking Argument Lists - The Python Tutorial

Answer from Jochen Ritzel on Stack Overflow
🌐
Sling Academy
slingacademy.com › article › python-passing-a-list-to-a-function-as-multiple-arguments
Python: Passing a List to a Function as Multiple Arguments - Sling Academy
def process_data(*args, **kwargs): # Process individual arguments for arg in args: print("Processing argument:", arg) # Process keyword arguments for key, value in kwargs.items(): print("Processing keyword argument:", key, "=", value) # Create a list and dictionary my_list = [1, 2, 3] my_dict = {"name": "Frienzied Flame", "age": 1000} # Pass the list and dictionary as multiple arguments to the function process_data(*my_list, **my_dict) ... Processing argument: 1 Processing argument: 2 Processing argument: 3 Processing keyword argument: name = Frienzied Flame Processing keyword argument: age = 1000 · That’s it. Happy coding! Next Article: Python: Generate a Dummy List with N Random Elements
Discussions

Passing an array/list into a Python function - Stack Overflow
The funniest part... while I appreciate S.Lott's care with words, Python lists are actually implemented as dynamic arrays... lol. ... This is unclear: is the intent to pass multiple arguments, created separately from the elements of the list? More on stackoverflow.com
🌐 stackoverflow.com
python - Converting list to *args when calling function - Stack Overflow
Check out this section in the Python tutorial for more info. ... I think the OP already knows this. The function takes multiple args but they have a single list they want to pass in as multiple args. More on stackoverflow.com
🌐 stackoverflow.com
python - How can I pass a list as a command-line argument with argparse? - Stack Overflow
I use nargs='*' as an add_argument parameter. I specifically used nargs='*' to the option to pick defaults if I am not passing any explicit arguments ... Please Note: The below sample code is written in python3. By changing the print statement format, can run in python2 · #!/usr/local/bin/python3.6 from argparse import ArgumentParser description = 'testing for passing multiple arguments and to get list ... More on stackoverflow.com
🌐 stackoverflow.com
How to pass a list as argument to map?
I don’t want to iterate the list argument. But, the following syntax iterates the list argument. How to not iterate the second list? def test(myVal, myList): return myVal * len(myList) list1 = [5, 2, 7, 6, 1] list2 = ['a', 'b', 'c'] result = map(test, list1, [list2]) resultList = list(result) ... More on discuss.python.org
🌐 discuss.python.org
0
0
December 19, 2023
🌐
W3Schools
w3schools.com › python › gloss_python_function_passing_list.asp
Python Passing a List as an Argument
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Expand and Pass a List and Dictionary As Arguments in Python | note.nkmk.me
August 19, 2023 - In Python, you can expand a list, tuple, and dictionary (dict) and pass their elements as arguments by prefixing a list or tuple with an asterisk (*), and prefixing a dictionary with two asterisks (** ...
Top answer
1 of 13
1688

SHORT ANSWER

Use the nargs option or the 'append' setting of the action option (depending on how you want the user interface to behave).

nargs

parser.add_argument('-l','--list', nargs='+', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 2345 3456 4567

nargs='+' takes 1 or more arguments, nargs='*' takes zero or more.

append

parser.add_argument('-l','--list', action='append', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 -l 2345 -l 3456 -l 4567

With append you provide the option multiple times to build up the list.

Don't use type=list!!! - There is probably no situation where you would want to use type=list with argparse. Ever.


LONG ANSWER

Let's take a look in more detail at some of the different ways one might try to do this, and the end result.

import argparse

parser = argparse.ArgumentParser()

# By default it will fail with multiple arguments.
parser.add_argument('--default')

# Telling the type to be a list will also fail for multiple arguments,
# but give incorrect results for a single argument.
parser.add_argument('--list-type', type=list)

# This will allow you to provide multiple arguments, but you will get
# a list of lists which is not desired.
parser.add_argument('--list-type-nargs', type=list, nargs='+')

# This is the correct way to handle accepting multiple arguments.
# '+' == 1 or more.
# '*' == 0 or more.
# '?' == 0 or 1.
# An int is an explicit number of arguments to accept.
parser.add_argument('--nargs', nargs='+')

# To make the input integers
parser.add_argument('--nargs-int-type', nargs='+', type=int)

# An alternate way to accept multiple inputs, but you must
# provide the flag once per input. Of course, you can use
# type=int here if you want.
parser.add_argument('--append-action', action='append')

# To show the results of the given option to screen.
for _, value in parser.parse_args()._get_kwargs():
    if value is not None:
        print(value)

Here is the output you can expect:

$ python arg.py --default 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ python arg.py --list-type 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567

$ # Quotes won't help here... 
$ python arg.py --list-type "1234 2345 3456 4567"
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']

$ python arg.py --list-type-nargs 1234 2345 3456 4567
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]

$ python arg.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']

$ python arg.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]

$ # Negative numbers are handled perfectly fine out of the box.
$ python arg.py --nargs-int-type -1234 2345 -3456 4567
[-1234, 2345, -3456, 4567]

$ python arg.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']

Takeaways:

  • Use nargs or action='append'
    • nargs can be more straightforward from a user perspective, but it can be unintuitive if there are positional arguments because argparse can't tell what should be a positional argument and what belongs to the nargs; if you have positional arguments then action='append' may end up being a better choice.
    • The above is only true if nargs is given '*', '+', or '?'. If you provide an integer number (such as 4) then there will be no problem mixing options with nargs and positional arguments because argparse will know exactly how many values to expect for the option.
  • Don't use quotes on the command line1
  • Don't use type=list, as it will return a list of lists
    • This happens because under the hood argparse uses the value of type to coerce each individual given argument you your chosen type, not the aggregate of all arguments.
    • You can use type=int (or whatever) to get a list of ints (or whatever)

1: I don't mean in general.. I mean using quotes to pass a list to argparse is not what you want.

2 of 13
157

I prefer passing a delimited string which I parse later in the script. The reasons for this are; the list can be of any type int or str, and sometimes using nargs I run into problems if there are multiple optional arguments and positional arguments.

parser = ArgumentParser()
parser.add_argument('-l', '--list', help='delimited list input', type=str)
args = parser.parse_args()
my_list = [int(item) for item in args.list.split(',')]

Then,

python test.py -l "265340,268738,270774,270817" [other arguments]

or,

python test.py -l 265340,268738,270774,270817 [other arguments]

will work fine. The delimiter can be a space, too, which would though enforce quotes around the argument value like in the example in the question.

Or you can use a lambda type as suggested in the comments by Chepner:

parser.add_argument('-l', '--list', help='delimited list input', 
    type=lambda s: [int(item) for item in s.split(',')])
Find elsewhere
🌐
Note.nkmk.me
note.nkmk.me › home › python
*args and **kwargs in Python (Variable-Length Arguments) | note.nkmk.me
May 12, 2025 - ... See the following article for the basics of functions in Python. ... Additionally, using * and ** when calling a function allows you to unpack and pass lists and dictionaries as arguments.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-argparse-pass-multiple-arguments-as-list
Python argparse: Pass a List as command-line argument | bobbyhadz
April 13, 2024 - If you need to pass a list of integers as a command line argument, set the type argument to int. ... Copied!import argparse parser = argparse.ArgumentParser( description='A sample Argument Parser.'
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-pass-multiple-arguments-to-function
How to pass multiple arguments to function ? - GeeksforGeeks
July 3, 2024 - The non-asterisk argument is always used before the single asterisk argument and the single asterisk argument is always used before the double-asterisk argument in a function definition. ... The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc.) and returns a list of results or map object. Syntax : map( function, iterable ) Parameters : function: The function which is going to execute for each iterableiterable ... In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code.
🌐
Toppr
toppr.com › guides › computer-science › programming-with-python › lists › lists-as-arguments
Python Passing a Lists as Arguments: Definition and Concepts
May 25, 2021 - In Python, we can easily expand the list, tuple, dictionary as well as we can pass each element to the function as arguments by the addition of * to list or tuple and ** to dictionary while calling function.
🌐
Python.org
discuss.python.org › python help
How to pass a list as argument to map? - Python Help - Discussions on Python.org
December 19, 2023 - How to not iterate the second list? def test(myVal, myList): return myVal * len(myList) list1 = [5, 2, 7, 6, 1] list2 = ['a', 'b', 'c'] result = map(test, list1, [list2]) resultList = list(result) ...
🌐
Real Python
realpython.com › python-kwargs-and-args
Python args and kwargs: Demystified – Real Python
November 7, 2023 - This can be inconvenient, especially if you don’t know up front all the values that should go into the list. This is where *args can be really useful, because it allows you to pass a varying number of positional arguments. Take the following example: ... def my_sum(*args): result = 0 # Iterating over the Python args tuple for x in args: result += x return result print(my_sum(1, 2, 3))
🌐
LabEx
labex.io › tutorials › python-how-to-pass-list-as-argument-in-python-421192
How to pass list as argument in Python | LabEx
By mastering list arguments, you'll enhance your Python programming skills in LabEx environments, creating more flexible and powerful functions. ## Append: Add to end of list fruits = ['apple', 'banana'] fruits.append('cherry') ## Insert: Add at specific position fruits.insert(1, 'blueberry') ## Extend: Add multiple elements fruits.extend(['date', 'elderberry'])
🌐
Hutsons-hacks
hutsons-hacks.info › working-with-multiple-arguments-in-a-python-function-using-args-and-kwargs
Working with multiple arguments in a Python function using args and kwargs – Hutsons-hacks
March 4, 2025 - The first example I will show is how to unpack a list of values and pass these unpacked arguments as seperate parameters into a sum function: ... I use the special * (args asterisk) to say I want to unpack each one of the values in the list and pass these as the parameters to the function – so 20 becomes x1, 40 becomes x2 and 20 becomes x3.
🌐
Studytonight
studytonight.com › python-howtos › pass-a-list-to-a-function-to-act-as-multiple-arguments
Pass a List to a Function to act as Multiple Arguments - Studytonight
February 16, 2021 - This concept of passing a single list of elements as multiple arguments is known as Unpacking Argument List. We use *args to unpack the single argument into multiple arguments. We use the unpacking operator * when arguments are not available ...
🌐
sqlpey
sqlpey.com › python › top-4-ways-to-pass-a-list-to-a-function-as-multiple-arguments-in-python
Top 4 Ways to Pass a List to a Function as Multiple Arguments in Python
December 5, 2024 - If prefer more control over how the lists are processed, you could always loop through the list and pass each argument individually: my_list = ['red', 'blue', 'orange'] for item in my_list: function_that_needs_strings(item) # called separately · While this method is less elegant than using unpacking, it can be useful in some cases where you want to maintain additional logic while calling the function. A: Unpacking in Python refers to the process of separating elements of a collection (like lists or tuples) and passing them as individual arguments to a function using the * or ** operators.
🌐
Delft Stack
delftstack.com › home › howto › python › pass a list to a function in python
How to Pass a List to a Function in Python | Delft Stack
February 2, 2024 - In Python, we can use *args to pass a variable number of arguments to a function. Now, since a list has multiple values, people tend to use *args as the parameter variable for a list argument so that all the values of the list are taken care of.