I have a long list of stings which need to be passed into a function as integers. What I am doing right now is:
my_function(int(list[0]), int(list[1]), int(list[2]), int(list[3])...)
But I know I can make a much shorter function call by unpacking the list:
my_function(*list)
I was wondering if there was a way to combine int()
casting with list unpacking *
, something like this:
my_function(*int(list)) #Doesn't work
If the number of variables is less than the number of elements, it is possible to add an asterisk * to the variable name and assign the remaining elements as a list. This will be described later. You can also unpack a nested tuple and list. If you want to expand the inner element, enclose the variable with () or [].
Unpacking assigns elements of the list to multiple variables. Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list. Did you find this tutorial helpful ?
In order to perform an unpack operation, the streaming operator must be used on the left hand side of an assignment. The article’s sections below detail typical unpacking operations: 1. Unpacking an int into byte variables 2. Unpacking a packed array into an unpacked array 3. Unpacking an array of bytes 3.1.
6. Unpacking a structure into another structure or a class 1. Unpacking an int into byte variables A 32-bit int variable can be unpacked into four byte (8-bit) variables in the following way: If only three byte variables are used (a, b, and c), the least significant byte of the int variable (0xFF) will be discarded.
Use the built-in method map
, e.g.
my_function(*map(int, list))
Alternatively, try list-comprehension:
my_function(*[int(x) for x in list])
BTW:
Please don't use list
as name for a local variable, this will hide the built-in method list
.
It is common use to append an underscore for variable-names that would otherwise hide built-in methods / conflict with keywords.
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