<br><br><div class="gmail_quote">On Wed, Mar 18, 2009 at 11:26 AM, Walther Neuper <span dir="ltr"><<a href="mailto:neuper@ist.tugraz.at">neuper@ist.tugraz.at</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Hi,<br>
<br>
loving Java (oo) as well as SML (fun) I use to practice both of them separately.<br>
Now, with Python I would like to combine 'oo.extend()' with 'functional map':<br>
<br>
Python 2.4.4 (#2, Oct 22 2008, 19:52:44)<br>
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2<br>
Type "help", "copyright", "credits" or "license" for more information.<br>
>>> def reverse_(list):<br>
...     """list.reverse() returns None; reverse_ returns the reversed list"""<br>
...     list.reverse()<br>
...     return list<br>
...<br>
>>> ll = [[11, 'a'], [33, 'b']]<br>
>>> l = ll[:]  # make a copy !<br>
>>> l = map(reverse_, l[:])  # make a copy ?<br>
>>> ll.extend(l)<br>
>>> print("ll=", ll)<br>
('ll=', [['a', 11], ['b', 33], ['a', 11], ['b', 33]])<br>
<br>
But I expected to get ...<br>
('ll=', [[11, 22], [33, 44], [22, 11], [44, 33]])<br>
... how would that elegantly be achieved with Python ?<br>
</blockquote></div><br><br>Hi, I will try to give you some comments.<br><br>First of all, don't use "list" as a name, since it masks the real list.<br><br>When you do l = map(reverse_, l[:]), you are applying reverse_ to each item of l. A more idiomatic approach would be:<br>
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.<br><br>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.<br>
<br>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.<br><br>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:<br>
<br>def reverse_(a_list):<br>    """list.reverse() returns None; reverse_ returns the reversed list"""<br>    a_list = a_list[:] # copy the list - try omitting this line and you will get your previous behaviour <br>
    a_list.reverse() # reverse the copied list in place<br>    return a_list # return the reversed list<br><br>list_of_lists = [[11, 'a'], [33, 'b']]<br><br>l = map(reverse_, list_of_lists)  <br>list_of_lists.extend(l)<br>
<br>print "list_of_lists=", list_of_lists # second half is reverted, first hals is not.<br><br>This will output:<br>list_of_lists= [[11, 'a'], [33, 'b'], ['a', 11], ['b', 33]]<br>
<br>Hope this helps.<br><br>bye<br>Francesco<br>