4

I have a simple for loop:

for index, (key, value) in enumerate(self.addArgs["khzObj"].nodes.items()):

and I want to start a new wx horizontal boxsizer after every 3rd item to create a panel with 3 nodes each and going on for as many as are in nodes. The obvious solution is to do:

if index % 3 == 0: add a horizontal spacer

but the enumerate starts at 0, so 0 % 3 == 0 and it would start a new row right off the bat. I've tried doing:

if index == 0: index = index + 1

but of course that doesn't work because it creates a new var instead of changing the original -- so I get 1, 1, 2, 3, 4, etc and that won't work because I'll get 4 nodes before I hit a index % 3 == 0.

Any suggestions on how to do this? This isn't a big enumerate, usually only about 10-15 items. Thanks.

linus72982
  • 1,418
  • 2
  • 16
  • 31

2 Answers2

19

Since Python 2.6, enumerate() takes an optional start parameter to indicate where to start the enumeration. See the documentation for enumerate.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
3

You are going to hate this answer for how obvious it is, but you could just do:

if index % 3 == 2: add a horizontal spacer

This adds the spacer after the 2nd element (which is actually the third), and every third element after it.

  • I didn't notice that -- fancy. I marked Daniel's as correct, though, because it's a bit more explicit and it helps me in other situations that aren't so neat and tidy ;) – linus72982 Mar 08 '15 at 02:21
  • His solution is certainly nifty. –  Mar 08 '15 at 02:23