0

See the following minimum code,

import numba
list_of_list = [[1, 2], [34, 100]]
@numba.njit()
def test(list_of_list):
    if 1 in list_of_list[0]:
        return 'haha'

test(list_of_list)

This won't work and it seems that list_of_list[0] is no longer behaves like a list during compile. However, the following code works:

list_of_list = [[1, 2], [34, 100]][0] # this is a list NOW!
@numba.njit()
def test(list_of_list):
    if 1 in list_of_list:
        return 'haha'

test(list_of_list)

This time, what I pass into is actually list, NOT list of list. Then it works. It seems for i in list works in numba, not for i in list_of_list.

In my use case, passing list of list or array like 2d data into numba function is common. Sometimes I only need one element in the list, which is dynamically determined in the program.

In order to make it work, I actually worked out a solution: making list_of_list flattened into a long list, then use linear index to extract one element in original list_of_list.

I am asking here, is there other alternative solutions?

Jiadong
  • 1,822
  • 1
  • 17
  • 37
  • 1
    Why are you storing array like 2d data in lists of lists instead of a numpy array? Numba can't work directly on lists, they are converted in an internal representation which is quite costly and comes with some limitations (same dtype -> the second example will fail if you put a float inside, no list of lists..) https://numba.pydata.org/numba-doc/dev/reference/pysupported.html – max9111 Dec 07 '18 at 03:28
  • stored in numpy array, is the same, `if 1 in array2d[0]` won't work... – Jiadong Dec 07 '18 at 03:30

2 Answers2

2

The in method works on sets. Returning a string can also cause some problems.

Working example

import numba as nb
import numpy as np

array_2D = np.array([[1, 2], [34, 100]])

@nb.njit()
def test(array_2D):
    if 1 in set(array_2D[0]):
        #Strings also causes sometimes problems
        #return 'haha'
        return(1)
    else:
        return(-1)
max9111
  • 6,272
  • 1
  • 16
  • 33
0

You can return a string with my revised version. It passed test and worked successfully.

from numba import njit
import numpy as np


@njit
def test():
    if 1 in set(np_list_of_list[0]):
        return 'haha'


if __name__ == '__main__':
    list_of_list = [[1, 2], [34, 100]]
    np_list_of_list = np.array(list_of_list)
    print(test()) 
Yagmur SAHIN
  • 277
  • 3
  • 3