Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack list and cast at the same time

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
like image 447
BloonsTowerDefence Avatar asked Feb 04 '13 16:02

BloonsTowerDefence


People also ask

How do I unpack a tuple and list of variables?

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 [].

How to unpack a list in Python?

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 ?

How do I perform an unpack operation in Java?

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.

How to unpack a structure into another structure or class?

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.


1 Answers

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.

like image 167
Thorsten Kranz Avatar answered Oct 21 '22 08:10

Thorsten Kranz