[Tutor] iteritems() for a list

Abel Daniel abli@freemail.hu
Sun Jun 29 20:16:01 2003


Tim Johnson wrote:
> >>> def gen(N):
> ...     for i in range(0,N,2):
> ...             yield i,i + 1
> ...
> 
> and then I'll try
> >>> def gen(L):
> ...     for i in range(0,len(L),2):
> ...             yield L[i],L[i + 1]
> 
> That will get me started. Thanks!
> regards
I think if you use range just so that you can do a subscription with the
loop variable (as in "for i in range(<something>)" and using i only for
subscription in the loop body), you aren't using the full power of the
"for" loop.

Anyway, here is my solution:

def f(l):
    flag = False
    for i in l:
        if flag:
            yield j,i
            flag = not flag
        else: 
            j = i 
            flag = not flag

Which is better for two reasons:

- it doesn't die with an IndexError on sequences which have an odd
  lenght, for example:
  >>> for i in gen(range(5)):
  ...  print i
  ... 
  (0, 1)
  (2, 3)
  Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in gen
  IndexError: list index out of range

- it doesn't depend on the sequence having a len, or being subscriptable.
  For example contrast:
  >>> for i in gen(gen(range(20))):
  ...  print i
  ... 
  Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in gen
  TypeError: len() of unsized object

  with:
  >>> for i in f(f(range(20))):
  ...  print i
  ... 
  ((0, 1), (2, 3))
  ((4, 5), (6, 7))
  ((8, 9), (10, 11))
  ((12, 13), (14, 15))
  ((16, 17), (18, 19))

Ok, enough nit-picking for today. :)
Have fun!

Abel Daniel
p.s.
Your e-mail address bounces with "Access denied"