0

Which code will be more efficient :

    list = [1,2,3,4,5]
    print(reverse(list))
    print(list[::-1])

Or is there any other more efficient method to reverse a list?

  • What do you mean by efficient, exactly? Note, `reversed` doesn't reverse a list really, it returns an iterator that iterates over a list in reverse order. Note, `mylist[::-1]` creates a new list, you want `mylist.reverse()` to reverse in-place, and there really is no more efficient method than that – juanpa.arrivillaga Aug 31 '20 at 05:54
  • second code will be better – Bhaskar pal Aug 31 '20 at 05:55
  • 1
    @Bhaskarpal why do you say so? they do two different things, and which is better depends on the result you want – juanpa.arrivillaga Aug 31 '20 at 05:56
  • @Selcuk i'm not entirely sure what the OP is asking, so I'm not sure if that is a good duplicate, it may be, but the question isn't really clear – juanpa.arrivillaga Aug 31 '20 at 06:00
  • @juanpa.arrivaillaga Because [::-1] will work in tuple,string as well where as where as well – Bhaskar pal Aug 31 '20 at 06:00
  • @juanpa.arrivillaga Weird, I had added another duplicate but it seems to have disappeared. Linked it again. – Selcuk Aug 31 '20 at 06:02
  • @Bhaskarpal The data structure in the question is certainly a `list`. Even the question title mentions "when working on lists". – Selcuk Aug 31 '20 at 06:03
  • @Selcuk I removed it because I thought it was even less relevant, it was about reversing strings, and a dubious lack of time difference the OP was seeing, i.e., they said `"".join(reversed(mystring))` was as fast as `mystring[::-1]` and it definitely isnt' – juanpa.arrivillaga Aug 31 '20 at 06:03
  • @Bhaskarpal so what? Why does that make it better? Note, `reversed` *also* works on tuples, strings, and other built-in sequences, along with `dict`, `dict.items()`, and `dict.values()` in more recent versions. In any case, that doesn't seem relevant to why it is "better". – juanpa.arrivillaga Aug 31 '20 at 06:04
  • @juanpa.arrivillaga Fair enough. But the second duplicate is certainly relevant as the answers benchmark both methods and discuss pros and cons. – Selcuk Aug 31 '20 at 06:04
  • @juanpa.arrivillaga I was just says as that would be applicable in the rest and would be more useful instead only only one or the cases – Bhaskar pal Aug 31 '20 at 06:04
  • 1
    @Bhaskarpal no, it's actually *less* applicable in current versions (3.8+), and similarly applicable in previous versions, but again, *it's doing something different* so whether it is better or not depends on the context – juanpa.arrivillaga Aug 31 '20 at 06:05
  • @juanpa.arrivillaga yes, understood – Bhaskar pal Aug 31 '20 at 06:09

0 Answers0