Why does foo function bellow work and bar one does not? What am I missing here?
@numba.njit
def foo(x):
return [[i for i in range(0)] for _ in range(x)]
@numba.njit
def bar(x):
return [[] for _ in range(x)]
You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.
Creating and returning lists from JIT-compiled functions is supported, as well as all methods and operations. Lists must be strictly homogeneous: Numba will reject any list containing objects of different types, even if the types are compatible (for example, [1, 2.5] is rejected as it contains a int and a float ).
In python, an empty list is defined as the list with no elements or items on the list. To define an empty list in Python, there are two ways to do this, and they are done either by using square bracket [] or by using a list constructor such as list().
1 Answer 1. bar creates an empty list. numba needs to infer the types of all variables that are used in nopython mode to compile your code (and njit only compiles to nopython mode). But an empty list cannot be typed, since numba won't be able to infer the type of the items stored in the list (since there are none).
Alternatively, you can create an empty list with the type constructor list (), which creates a new list object. If no argument is given, the constructor creates a new empty list, [].
Empty lists are falsy values, which means that they evaluate to False in a boolean context: You can add elements to an empty list using the methods append () and insert ():
To create a list of lists in python, you can use the square brackets to store all the inner lists. For instance, if you have 5 lists and you want to create a list of lists from the given lists, you can put them in square brackets as shown in the following python code.
bar
creates an empty list. numba needs to infer the types of all variables that are used in nopython
mode to compile your code (and njit
only compiles to nopython mode). But an empty list cannot be typed, since numba won't be able to infer the type of the items stored in the list (since there are none). Just try the following to get a more "descriptive" error message:
numba.typeof([])
If you use object mode (for example with the jit
decorator without specifying nopython=True
), you can use untyped python objects, at the cost of a slower execution performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With