# How to transfer a list as a Python function argument

This issue was already discussed here, but the answer is unclear yet. I use very simple Python function for converting a string list to upper case

def ListToUpper(wrd_lst):
string_list=wrd_lst
for i in range(len(wrd_lst)):
string_list[i] =string_list[i].upper()
return string_list


Code ListToUpper(['a','b']) works in Python as needed. But Mathematica displays an error when one calls (ss -- session)

ExternalEvaluate[ss, <| "Command" -> "ListToUpper","Arguments" -> {"['a', 'b']"} |>]


It's strange, as the argument ['a', 'b'] is the same for both calls. In the case, when argument is a scalar (or string), all works properly

• What error does it display? Please add it to the question. Nov 24 '21 at 11:27
• "This issue was already discussed here, but the answer is unclear yet." Which post are you refering to? Can you add the link to the question? Nov 24 '21 at 11:56

By taking advantage of Python's list comprehension capability, this method does not need to convert the tuple wrd_list to a list

ss = StartExternalSession["Python"]

listToUpper = ExternalFunction[ss, "def ListToUpper(wrd_lst):
return [i.upper() for i in wrd_lst]"];

listToUpper[{"a", "b"}]

(*   {A, B}  *)

• For me, it is desirable to use an external Python function, because I apply more comprehensive processing of a list (related to language stemming). I'm not sure that ExternalFunction will support external Python function in *.py file :(( Nov 24 '21 at 12:31
• @Konstantin why wouldn't it support that? Can you import the file that exports the function you want? Nov 24 '21 at 13:12
• The LouisB's code works fine for my problem of stemming. But executing a Python file with ExternalEvaluate is more preferable for some reasons. For example, my Python file can include a number of functions, so they can be called by ExternalEvaluate[ss, <| "Command" -> "coms", "Arguments" -> {args} |>] without definition of new ExternalFunction for each Python function Nov 24 '21 at 17:41
• Thank you to all! The problem is solved by calling: ExternalEvaluate[ss, File["PythonFile"]]; ExternalEvaluate[ss, <| "Command" -> "com", "Arguments" -> {{arg1, arg2, ..., argn}} |>] Nov 24 '21 at 17:52

This works fine:

ss = StartExternalSession["Python"];
ListToUpper = ExternalFunction[ss, "def ListToUpper(wrd_lst):
string_list=list(wrd_lst)
for i in range(len(wrd_lst)):
string_list[i] = string_list[i].upper()
return string_list"];

ListToUpper[{"a", "b"}]

(* {"A", "B"} *)


Note that I used list(wrd_lst) as wrd_lst is passed as a tuple and tuples are immutable later on at the point string_list[i] = ... so you must convert to a mutable list first.