Is there a better algorithm?

J Kenneth King james at
Fri Jan 2 21:57:22 CET 2009

Kottiyath <n.kottiyath at> 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.

Aside from the typical workarounds that first came to mind, I started
wondering whether it was possible to expose the problem and solve it

Sadly, it appears to be non-trivial (or at least, well hidden from the
unwashed masses).

I'd be really curious if the unpacking machinery were exposed to the
developer. I started poking around the operator and types modules, but
the implementation isn't obvious. What methods are being called on the
operands by the assignment operator in the following statement:

a, b, c = some_tuple

I'm sorry if this line of inquiry is not very pythonic; but one is
curious if this is some python magic happening here. After using the
idiom for years I hadn't really thought about it much until recently.

More information about the Python-list mailing list