Reputation: 1204
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
Upvotes: 8
Views: 3181
Reputation: 12755
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.
Upvotes: 17