In a recent post, we discussed arrays and what they mean and how they differ from lists. When you have a list in an array, one of the things that you need to define is what data type it is. If you don’t then the array will throw the error that you are on this page to resolve.
On the Python.org website, below are the list of values that can be populated to indicate what the data type of a list is in an array.
If you don’t add in the value you will get the below error:
ValueError: bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)
Let’s look at an example
import array as test_array a = test_array.array([1,2,3]) print(a) Gives an error of: TypeError: array() argument 1 must be a unicode character, not list
As can be seen, the above logic tries to print a list within an array. The problem here is that an array can only be of one data type, and it has to be specified on the array creation.
How do we fix this?
It is quite simple! Before the list, we simply specify which type code we would like to apply from the above list. In this instance we are going to assign it as “signed int” that being the value “i” as follows:
import array as test_array a = test_array.array("i",[1,2,3]) print(a) Prints the following with no error: array('i', [1, 2, 3]) Process finished with exit code 0
I can change the value “i” to any of the values I want from the above list, just picked that one to show as an example.