Compact way to assign values by slicing list in Python
I have the following list
bar = ['a','b','c','x','y','z']
What I want to do is to assign 1st, 4th and 5th values of bar
into v1,v2,v3
,
is there a more compact way to do than this:
v1, v2, v3 = [bar[0], bar[3], bar[4]]
Because in Perl you can do something like this:
my($v1, $v2, $v3) = @bar[0,3,4];
Solution 1:
You can use operator.itemgetter
:
>>> from operator import itemgetter
>>> bar = ['a','b','c','x','y','z']
>>> itemgetter(0, 3, 4)(bar)
('a', 'x', 'y')
So for your example you would do the following:
>>> v1, v2, v3 = itemgetter(0, 3, 4)(bar)
Solution 2:
Assuming that your indices are neither dynamic nor too large, I'd go with
bar = ['a','b','c','x','y','z']
v1, _, _, v2, v3, _ = bar
Solution 3:
Since you want compactness, you can do it something as follows:
indices = (0,3,4)
v1, v2, v3 = [bar[i] for i in indices]
>>> print v1,v2,v3 #or print(v1,v2,v3) for python 3.x
a x y