Monday, September 8, 2008

Reversing lists and strings in python; third field in [] is for step

This is the simplest way to reverse a string or list in Python:


>>> "aoeu"[::-1]
'ueoa'


I was about to say this was pretty shitty because it doesn't follow any sort of pattern, it seems to be a special thing just out of nowhere. But then I tried -2, and -3. Turns out the third field is for step.


>>> "aoeu"[::-1]
'ueoa'
>>> "aoeu"[::-2]
'uo'
>>> "aoeu"[::-3]
'ua'
>>> "0123456789"[::]
'0123456789'
>>> "0123456789"[::1]
'0123456789'
>>> "0123456789"[::2]
'02468'
>>> "0123456789"[::3]
'0369'
>>> "0123456789"[::-1]
'9876543210'
>>> "0123456789"[::-2]
'97531'
>>> "0123456789"[::-3]
'9630'
>>> "0123456789"[2:4:-1]
''
>>> "0123456789"[4:2:-1]
'43'


So, with [4:10] it takes the 4th through 10th item in the list. With [4:10:2], it takes every other item from 4 to 10. With [4:10:3] it takes every third item, and so forth. With [4:10:-1], well it seems to do nothing, but with [10:4:-1] it takes every item from 4 through 10, but in reverse order. With [10:4:-2] it takes every other item in reverse order.

The more you know. No rainbows please.