python - How to use sequence unpacking with a sequence of variable length? -
if know length of list in advance, can use sequence unpacking assign variable elements of list thus:
my_list = [1,2,3] x, y, z = my_list
if don't know length of list in advance, how can assign variables elements of list using sequence unpacking? if argument's sake don't care how variables named, can first length of list , unpack amount of arbitrarily-named variables?
certainly not recommend possible:
my_list = [1, 2, 3] counter, value in enumerate(my_list): exec 'a{} = {}'.format(counter, value) print a0, a1, a2
output:
1 2 3
or use python 3:
>>> a, *rest = my_list >>> 1 >>> rest [2, 3]
Comments
Post a Comment