Useful list-indexing trick

Hi all,
I just found this while googling, and it sort of blew my mind. I'm writing in Python, but I guess you could use this in any language.

So if you've got a list of items you want to cycle through, it's obvious to go:

current_index += 1
if current_index >= len(l):
    current_index -= len(l)
elif current_index < 0:  # We can probably scroll back too.
    current_index += len(l)
# Do stuff.

Seems there is a quicker way, which seems to be foolproof, as well as a 1-liner:

current_index = (current_index + 1) % len(l)
# Do stuff

This works because the % operator does modulus, which is to say it returns the remainder of trying to shove the number on the left into the number on the right: 10 % 3 is 1, because 3's into 10 go a maximum of 3 times, with 1 left over.

Back to lists, given the listlike:

>>> l = ['first item', 'second item', 'third item']
>>> l[0 % len(l)]
'first item'
>>> l[1 % len(l)]
'second item'
>>> l[2 % len(l)]
'third item'
>>> l[3 % len(l)]
'first item'
>>> l[-1 % len(l)]
'third item'
>>> l[-2 % len(l)]
'second item'

My world has officially been rocked.



-- 
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector
  • ... AudioGames . net Forum — Developers room : chrisnorman7 via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : chrisnorman7 via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Ethin via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : chrisnorman7 via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Ethin via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector

Reply via email to