why i can't reverse a list of list in python -
i wanted code return list of none (i think it's because list.reverse() reversing list in place):
map(lambda row: row.reverse(), figure)
i tried one, reversed return iterator :
map(reversed, figure)
finally did , work me , don't know if it's right solution:
def reverse(row): """func reverse list not in place""" row.reverse() return row map(reverse, figure)
if has better solution i'm not aware of please let me know
kind regards,
the mutator methods of python's mutable containers (such .reverse
method of lists) invariably return none
-- few return 1 useful value, e.g. .pop
method returns popped element, key concept retain none of mutators returns mutated container: rather, container mutates in-place , return value of mutator method not container. (this application of cqs principle of design -- not quite fanatical as, say, in eiffel, language devised bertrand meyer, invented cqs, that's because in python "practicality beats purity, cfr import this
;-).
building list costlier building iterator, overwhelmingly common case want loop on result; therefore, built-ins such reversed
(and wonderful building blocks in itertools
module) return iterators, not lists.
but if therefore have iterator x
need equivalent list y
? piece of cake -- y = list(x)
. make new instance of type list
, call type list
-- such general python idea it's more crucial retain pretty-important stuff pointed out in first 2 paragraphs!-)
so, code specific problem easy put based on crucial notions in previous paragraphs:
[list(reversed(row)) row in figure]
note i'm using list comprehension, not map
: rule of thumb, map
should used last-ditch optimization when there no need lambda
build (if lambda
involved listcomp, being clearer usual, tends faster anyway!-).
once you're "past master of python", if profiling tells code bottleneck, can know try alternatives such as
[row[::-1] row in figure]
applying negative-step slicing (aka "martian smiley") make reversed copies of rows, knowing it's faster list(reversed(row))
approach. -- unless code meant maintained or @ least skilled @ python -- it's defensible position use simplest "code first principles" approach except profiling tells push down on pedal. (personally think "martian smiley" important enough avoid applying general philosophy specific use case, but, hey, reasonable people differ on specific point!-).
Comments
Post a Comment