Insert item before each element of a list

Prasad, Ramit ramit.prasad at jpmorgan.com
Mon Oct 8 18:12:38 EDT 2012


Agon Hajdari wrote:
> On 10/08/2012 11:15 PM, Prasad, Ramit wrote:
> > Agon Hajdari wrote:
> >>
> >> On 10/08/2012 09:45 PM, Chris Kaynor wrote:
> >>> [('insertme', i) for i in x]
> >>
> >> This is not enough, you have to merge it afterwards.
> >
> > Why do you say that? It seems to work just fine for me.
> >
> >>>> x
> > [0, 1, 2, 3, 4]
> >>>> [('insertme', i) for i in x]
> > [('insertme', 0), ('insertme', 1), ('insertme', 2), ('insertme', 3), ('insertme', 4)]
> >
> >>
> >> y = [item for tup in y for item in tup]
> 
> I think he wanted to have a 'plain' list
> a = [0, 1, 0, 2, 0, 3]
> and not
> a = [(0, 1), (0, 2), (0, 3)]

You are absolutely correct. I missed that when I tried it.
Instead of the nested list comprehension, I might have used
map instead.

>>> y = [('insertme', i) for i in x]
>>> z = []
>>> _ = map( z.extend, y )
>>> z
['insertme', 0, 'insertme', 1, 'insertme', 2, 'insertme', 3, 'insertme', 4]

I am not sure which is more Pythonic, but to me map + list.extend tells
me more explicitly that I am dealing with an iterable of iterables.
It might make more sense to only to me though.


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list