flat tuple

Phil Frost indigo at bitglue.com
Tue Sep 21 14:06:46 CEST 2004


Tuples can be joined with the + operator, like so:

>>> (1,2)+(3,4)
(1, 2, 3, 4)

so in your case, you could do (n,) + t. If you are using the result for
% formatting, it might be better to use a list, which is mutable, so
it's possible to add a new element without constructing a new list, like
so:

>>> t = [1,2,3]
>>> t.insert(0, 10)
>>> t
[10, 1, 2, 3]

If you have many things to concatenate, you can use the builtin function
reduce to do it, like so:

>>> l = [[1,2,3],[4,5],[6]]
>>> reduce(lambda a, b: a.extend(b) or a, l, [])
[1, 2, 3, 4, 5, 6]


On Tue, Sep 21, 2004 at 12:58:08PM +0100, Will McGugan wrote:
> Hi,
> 
> What is the simplest way of turning a single value and a tuple in to a 
> single 'flat' tuple?
> 
> ie.
> 
> t= ( 1, 2, 3 )
> n= 10
> 
> n, t gives me ( 10, ( 1, 2, 3 ) )
> 
> Fair enough, but I would like to get.. ( 10, 1, 2, 3 )
> 
> I would like to use the result to create a string with the % operator - 
> I was hoping there was some shorthand to produce ( n, t[0], t[1], t[2] ).
> 
> Thanks,
> 
> Will McGugan



More information about the Python-list mailing list