objectoriented -?- functional

Piet van Oostrum piet at cs.uu.nl
Wed Mar 18 16:59:59 CET 2009


>>>>> Walther Neuper <neuper at ist.tugraz.at> (WN) wrote:

>WN> Hi,
>WN> loving Java (oo) as well as SML (fun) I use to practice both of them
>WN> separately.
>WN> Now, with Python I would like to combine 'oo.extend()' with 'functional
>WN> map':

>WN> Python 2.4.4 (#2, Oct 22 2008, 19:52:44)
>WN> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
>WN> Type "help", "copyright", "credits" or "license" for more information.
>>>>> def reverse_(list):
>WN> ...     """list.reverse() returns None; reverse_ returns the reversed
>WN> list"""
>WN> ...     list.reverse()
>WN> ...     return list
>WN> ...
>>>>> ll = [[11, 'a'], [33, 'b']]
>>>>> l = ll[:]  # make a copy !
>>>>> l = map(reverse_, l[:])  # make a copy ?
>>>>> ll.extend(l)
>>>>> print("ll=", ll)
>WN> ('ll=', [['a', 11], ['b', 33], ['a', 11], ['b', 33]])

>WN> But I expected to get ...
>WN> ('ll=', [[11, 22], [33, 44], [22, 11], [44, 33]])
>WN> ... how would that elegantly be achieved with Python ?

I guess you later changed 22 to 'a' and 44 to 'b'.

You have made a copy of the outer list with ll[:] (actually twice) but
you have not made copies of the inner lists and these are the important
ones. So the reverse will reverse the *original* inner lists which are
both in ll and in l.

If you still want to do destructive reverses on the inner list you
should make a deep copy:

>>> import copy
>>> l = copy.deepcopy(ll)
>>> l
[[11, 'a'], [33, 'b']]
>>> ll.extend(l)
>>> ll
[[11, 'a'], [33, 'b'], ['a', 11], ['b', 33]]

But IMHO it would be better to use non-destructive reverses:

>>> ll
[[11, 'a'], [33, 'b']]
>>> l = [list(reversed(x)) for x in ll]
>>> l
[['a', 11], ['b', 33]]
>>> ll.append(l)
>>> ll
[[11, 'a'], [33, 'b'], [['a', 11], ['b', 33]]]

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list