Thursday, June 11, 2009

python: how to flatten a tuple

Basically the problem was that I wanted to create a flat tuple from a tuple and a single value like such:

val = 3
tup = ( 'a', 3.14, "zzz" )


I wanted this:

( 3, 'a', 3.14, "zzz" )

not this:

( 3, ( 'a', 3.14, "zzz" ) )


It turns out that this is exactly what the '+' operator does for tuples.

In general, adding two tuples creates a bigger flat tuple from the elements of each.
For this problem the answer then was:


(val,) + tup

Easy. :)


Note:

(val,) results in a tuple with a single element.



Ad: Python books on Amazon

2 comments:

Anonymous said...

Thanks! Been searching for this solution for about 20 minutes, seems these kinds of problems always get me.

rr said...

You're welcome!