Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

reversed(a) and a[::-1] are not equivalent. The former produces an iterator over the given list (with all the mutability dangers that come with it), while the latter produces a copied list. For plain iteration, you're correct, reversed() is better (similar to how xrange vs. range was back in the day); however, for reversing something and keeping it around, the slice syntax is better.

    >>> reversed([1, 2, 3])
    <listreverseiterator object at 0x107265650>
    >>> [1, 2, 3][::-1]
    [3, 2, 1]
To clarify your point, list(reversed(a)) and a[::-1] are equivalent. It's a slightly subtle point, but extremely important if you're keeping the result of reversed() around for any length of time. If you're just iterating at the moment that you use it, yes, they're effectively equivalent.


list(reversed(a))




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: