Is there a better algorithm?

Ned Deily nad at acm.org
Fri Jan 2 22:19:31 CET 2009


In article <85aba9h1e5.fsf at dozer.localdomain>,
 J Kenneth King <james at agentultra.com> wrote:
> Kottiyath <n.kottiyath at gmail.com> writes:
> > I have the following list of tuples:
> > L = [(1, 2), (3, 4, 5), (6, 7)]
> >
> > I want to loop through the list and extract the values.
> > The only algorithm I could think of is:
> >>>> for i in l:
> > ...  u = None
> > ...  try:
> > ...   (k, v) = i
> > ...  except ValueError:
> > ...   (k, u, v) = i
> > ...  print k, u, v
> > ---------
> > 1 None 2
> > 3 4 5
> > 6 None 7
> > -------------
> > But, this algorithm doesnt look very beautiful - like say -> for k, u,
> > v in L:
> > Can anyone suggest a better algorithm to get the values?
> 
> Just a note: this isn't really an algorithm problem. ;)
> 
> It's more of a grammar obstruction.
> 
> To make your code more simple, it would be nice if the assignment
> operator would return, "None," in the case where there are too few
> values to unpack from the right-operand of the assignment operator.

Looks like the extended iterable unpacking feature of Python 3.0, 
described in PEP 3132, comes to the rescue here:

>>> L = [(1, 2), (3, 4, 5), (6, 7)]
>>> for i in L:
...     k, *u, v = i
...     print(k, u, v)
... 
1 [] 2
3 [4] 5
6 [] 7

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list