I'd be interested in hearing people's stories of Eureka moments in Python,
moments where you suddenly realise that some task which seemed like it
would be hard work was easy with Python.

I had a recent one, where I had spent some time creating a function which
took a list as an argument, and then rearranged the items according to
what magicians call a Monge shuffle. I had started off with a piece of
code that walked the list, dropping items into two new lists, then
combining them again. I got the code down to eight lines or so, something
like this:

# from memory, untested
top, bottom = True, False # not strictly needed, but helps document code
where = bottom
holder = {top: [], bottom: []}
for item in reversed(alist):
    holder[where].append(item)
    where = not where
holder[bottom].reverse()
print holder[bottom] + holder[top]


And then it suddenly struck me that I could do it as a one-liner:

alist[1::2] + list(reversed(alist[0::2]))

Or if I wanted to be even more concise, if slightly less readable:

alist[1::2] + alist[0::2][::-1]

If only a real Monge shuffle with actual cards was so easy...




-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to