[Ilugc] Python list.reverse() [was: Re: [Fwd: [ilugcbe] Fifth Meeting Pics & Sri Shakthi Institute of Engineering and Technology updated in Open Street Map]]

  • From: damodaran.balaji@xxxxxxxxx (openbala)
  • Date: Fri, 18 Feb 2011 10:49:55 +0530

On Tue, Feb 15, 2011 at 2:25 PM, Noorul Islam K M <noorul at noorul.com> wrote:

openbala <damodaran.balaji at gmail.com> writes:

On Mon, Feb 14, 2011 at 12:52 PM, Kenneth Gonsalves
<lawgon at thenilgiris.com> wrote:


What is wrong below?


There is nothing wrong. Certain programming languages try to handle
certain things differently.
There is a new wave of languages that take immutability and
referential transparency very seriously. (please use your favourite
search engine to figure out what they are)

The gist of immutability is that any operations on a data structure
should not change its data structure. (for e.g. java's String class is
immutable)
In python the "reverse()" method is mutating the list instead of
returning a new output.

This is the output in ruby:

$ numbers = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
$ numbers.reverse
=> [5, 4, 3, 2, 1]
$ numbers
=> [1, 2, 3, 4, 5]
$

Note that the numbers list has not changed even after calling 'reverse' method.

The general consensus is that mutability is bad for programming. YMMV.

numbers = [1, 2, 3, 4, 5]
numbers.reverse()
numbers
[5, 4, 3, 2, 1]
list.reverse(numbers)
numbers
[1, 2, 3, 4, 5]

Thanks and Regards
Noorul

Other related posts: