Create a numba typed List without looping over a python list

Question:

I want to use a numba.typed.List (going to call it List) to pass into my function which is wrapped in njit. However this List should be created from an existing python list.

When I look at the documentation it seems the way you create a List is to initialize it and then append elements to it. However this requires you to loop over an already existing list in python which seems inefficient for large lists.

For example:

from numba.typed import List
numba_list = List()
py_list = ["a", "b", "c"]
for e in py_list:
    numba_list.append(e)

In [17]: numba_list[0]
Out[17]: 'a'

Is there a way to set a List to the values of a python list without explicitly looping over the python list ?

I am using numba.__version__ = ‘0.47.0’

Asked By: RK1

||

Answers:

You can use list comprehension for typed lists the following way:

from numba.typed import List
numba_list = List()
py_list = ["a", "b", "c"]
[numba_list.append(e) for e in py_list]
print(numba_list)

Output:

ListType[unicode_type]([a, b, c])

Figured this from an example at Numba Deprecation Notice.

Answered By: sudesh

I am working on numba 0.49.1 where you can pass the list by the construction.

py_list = [2,3,5]    
number_list = numba.typed.List(py_list)
Answered By: Tobias Senst

if you are dealing with numeric values, why not use numpy array?

import numpy as np
py_list = [1, 2, 3, 4]
np_array = np.array(py_list)
Answered By: user1431213
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.