Perl's @foo[3,7,1,-1] ?
no.email at please.post
Sat Jun 13 20:11:11 CEST 2009
Switching from Perl here, and having a hard time letting go...
Suppose I have an "array" foo, and that I'm interested in the 4th, 8th,
second, and last element in that array. In Perl I could write:
my @wanted = @foo[3, 7, 1, -1];
I was a bit surprised when I got this in Python:
>>> wanted = foo[3, 7, 1, -1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers
Granted, Perl's syntax is often obscure and hard-to-read, but in
this particular case I find it quite transparent and unproblematic,
and the fictional "pythonized" form above even more so.
The best I've been able to come up with in Python are the somewhat
>>> wanted = map(foo.__getitem__, (3, 7, 1, -1))
or the clearer but unaccountably sesquipedalian
>>> wanted = [foo[i] for i in 3, 7, 1, -1]
>>> wanted = [foo, foo, foo, foo[-1]]
Are these the most idiomatically pythonic forms? Or am I missing
More information about the Python-list