[Tutor] Skipping elements from inside generator loops

ibraheem umaru-mohammed iumarumo@eidosnet.co.uk
Thu, 1 Aug 2002 11:06:33 +0100


[Scot W. Stevenson wrote...]
<snip>...</snip>
-| 
-| Somehow, it doesn't seem right to be able to change what amounts to a loop 
-| counter from the inside, even though it is useful here. Fooling around 
-| some more, I find that you can not do this with "normal" for loops:
-| 
-| ===============================
-| for a in range(len(procession)):
-|     if procession[a] == 'ALARM!':
-|         a = a+1
-|     else:
-|         print procession[a]
-| ===============================
-| 

Hmmnn...This works for me:

	ibraheem@ignoramus:$ python2.2
	Python 2.2.1 (#1, Apr 25 2002, 14:21:58)
	[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
	Type "help", "copyright", "credits" or "license" for more information.
	rlcompleter2 0.9.6 activated
	>>> procession=['black cat',
	>>> ... 'white cat',
	>>> ... 'grey cat',
	>>> ... 'ALARM!',
	>>> ... 'evil dog',
	>>> ... 'fat cat',
	>>> ... 'slow cat']
	>>> for a in range(len(procession)):
	>>> ...   if procession[a] == 'ALARM!':
	>>> ...     a = a + 1
	>>> ...   else:
	>>> ...     print procession[a]
	>>> ...
	>>> black cat
	>>> white cat
	>>> grey cat
	>>> evil dog
	>>> fat cat
	>>> slow cat
	>>>
	
But I guess most people would use a 'continue' instead:

>>>for a in range(len(procession)):
>>>...   if procession[a] == 'ALARM!':
>>>...     continue
>>>...   else:
>>>...     print procession[a]
>>>...
>>>black cat
>>>white cat
>>>grey cat
>>>evil dog
>>>fat cat
>>>slow cat
>>>
>>>procession
>>>['black cat', 'white cat', 'grey cat', 'ALARM!', 'evil dog', 'fat cat', 'slow cat']
>>>

<snip>...</snip>

Kindest regards,

			--ibs.
-- 
			ibraheem umaru-mohammed
			   www.micromuse.com
			         --0--


-- 
			ibraheem umaru-mohammed
			   www.micromuse.com
			         --0--