[Tutor] Adding index numbers to tuple

Hugo Arts hugo.yoshi at gmail.com
Tue Aug 16 18:10:15 CEST 2011


On Tue, Aug 16, 2011 at 3:42 PM, Christian Witts <cwitts at compuscan.co.za> wrote:
> On 2011/08/16 03:10 PM, Timo wrote:
>
> Hello,
> Maybe a bit confusing topic title, probably the example will do.
>
> I have a tuple:
> t = ('a', 'b', 'c', 'd')
> And need the following output, list or tuple, doesn't matter:
> (0, 'a', 1, 'b', 2, 'c', 3, 'd')
>
> I tried with zip(), but get a list of tuples, which isn't the desired
> output. Anyone with a solution or push in the right direction?
>
> Cheers,
> TImo
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>>>> t = ('a', 'b', 'c', 'd')
>>>> new_t = zip(xrange(len(t)), t)
>>>> new_t
> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>>> from itertools import chain
>>>> list(chain.from_iterable(new_t))
> [0, 'a', 1, 'b', 2, 'c', 3, 'd']
>
> That would be for if you were using the zip way, but enumerate should be
> simpler as Martin pointed out.
>

You can sort of mix the two together:

>>> from itertools import chain
>>> t = ('a', 'b', 'c', 'd')
>>> list(chain.from_iterable(enumerate(t)))
[0, 'a', 1, 'b', 2, 'c', 3, 'd']
>>>


More information about the Tutor mailing list