enhancing slicing

Tim Peters tim.one at home.com
Mon Aug 27 15:39:48 EDT 2001


[Chris Barker, suggests gather subscripting]
> ...
> Now you have do do something like:
>
> >>> l2 = []
> >>> for i in indexes:
> ...     l2.append(l[i])
> ...
> >>> l2
> ['b', 'e', 'f', 'h']
>
> or with a list comprehension:
>
> >>> [l[i] for i in range(len(l)) if (i in indexes)]
                     ^^^^^^^^^^^^^^^^^^^^^^^       ^
> ['b', 'e', 'f', 'h']
>
> Both of which are far more wordy and confusing than my suggestion.

I put carets under the stuff you didn't need there; i.e.,

    [l[i] for i in indexes]

is the natural way to write this with listcomps.  A question is whether
that's a common enough need to justify masking what's currently a
TypeError -- you can't make a formerly exceptional case "mean something"
without tearing a hole in the type safety net.





More information about the Python-list mailing list