objectoriented -?- functional

Francesco Guerrieri f.guerrieri at gmail.com
Wed Mar 18 07:49:45 EDT 2009


On Wed, Mar 18, 2009 at 11:26 AM, Walther Neuper <neuper at ist.tugraz.at>wrote:

> Hi,
>
> loving Java (oo) as well as SML (fun) I use to practice both of them
> separately.
> Now, with Python I would like to combine 'oo.extend()' with 'functional
> map':
>
> Python 2.4.4 (#2, Oct 22 2008, 19:52:44)
> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def reverse_(list):
> ...     """list.reverse() returns None; reverse_ returns the reversed
> list"""
> ...     list.reverse()
> ...     return list
> ...
> >>> ll = [[11, 'a'], [33, 'b']]
> >>> l = ll[:]  # make a copy !
> >>> l = map(reverse_, l[:])  # make a copy ?
> >>> ll.extend(l)
> >>> print("ll=", ll)
> ('ll=', [['a', 11], ['b', 33], ['a', 11], ['b', 33]])
>
> But I expected to get ...
> ('ll=', [[11, 22], [33, 44], [22, 11], [44, 33]])
> ... how would that elegantly be achieved with Python ?
>


Hi, I will try to give you some comments.

First of all, don't use "list" as a name, since it masks the real list.

When you do l = map(reverse_, l[:]), you are applying reverse_ to each item
of l. A more idiomatic approach would be:
l = [reverse_(sub_list) for sub_list in l] which is called a list
comprehension. There is no need to make a copy of l.

Note that the individual sub lists in l and ll are still the same object in
your example, thus you are reverting also the items of ll.

As a last thing, note that print in python 2.4 (which you are using) is not
a function and so you don't have to put parentheses around what you wish to
print.

Althugh this particular example is much better server by other Pythonic
techniques, for the sake of it, give a look at this small script which is a
rewrite of yours but should be doing what you expected:

def reverse_(a_list):
    """list.reverse() returns None; reverse_ returns the reversed list"""
    a_list = a_list[:] # copy the list - try omitting this line and you will
get your previous behaviour
    a_list.reverse() # reverse the copied list in place
    return a_list # return the reversed list

list_of_lists = [[11, 'a'], [33, 'b']]

l = map(reverse_, list_of_lists)
list_of_lists.extend(l)

print "list_of_lists=", list_of_lists # second half is reverted, first hals
is not.

This will output:
list_of_lists= [[11, 'a'], [33, 'b'], ['a', 11], ['b', 33]]

Hope this helps.

bye
Francesco
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090318/11e1d832/attachment-0001.html>


More information about the Python-list mailing list