Perl's @foo[3,7,1,-1] ?

Jack Diederich jackdied at gmail.com
Sat Jun 13 21:17:56 CEST 2009


On Sat, Jun 13, 2009 at 2:11 PM, kj<no.email at please.post> wrote:
>
>
> 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
> Perl-like-in-its-obscurity:
>
>>>> 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[3], foo[7], foo[7], foo[-1]]
>
> Are these the most idiomatically pythonic forms?  Or am I missing
> something better?
>

There is only so much room in the syntax for common cases before you
end up with ... perl (no offense intended, I'm a perl monk[1]).   The
Python grammar isn't as context sensitive or irregular as the perl
grammar so mylist[1,2,3]  so the "1,2,3" tuple is always interpreted
as a tuple and the square brackets always expect an int or a slice.
Not including special cases everywhere means there isn't a short way
to handle special cases but it also means human readers have to
remember fewer special cases.   Perl and Python make different
tradeoffs in that respect.


-Jack

[1] http://www.perlmonks.org/?node_id=111952



More information about the Python-list mailing list