Search code examples
javapythonandroidchaquopy

Chaquopy: Convert Java ArrayList/LinkedList to Python Array


Good evening guys,

yesterday I found out that we can use Chaquopy to run Python scripts from Java. I have played around with it a little bit and came across the following problem:

ArrayList-Objects (resp. LinkedList-Objects), which I have passed to a Python script, do not behave as I would expect it. In Python, I can't just use list[index] with an ArrayList, that comes from Java. The following exception is thrown:

com.chaquo.python.PyException: TypeError: 'LinkedList' object is not subscriptable

I have looked at the Chaquopy-Documentation and couldn't find any information about Java-List support. Only arrays are stated there.

Now my question: Do I have to convert all my lists to arrays in Java before passing them to Python?

Thank you all


Solution

  • You're right, Chaquopy supports accessing Java arrays using Python syntax, but not Java Lists. You can either:

    • Copy the List to an array using toArray, and pass that to Python; or
    • Pass the List to Python and have the Python code call its methods directly (i.e.size, get, etc.).