Insert item before each element of a list
ramit.prasad at jpmorgan.com
Tue Oct 9 00:12:38 CEST 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
>>> y = [('insertme', i) for i in x]
>>> z = 
>>> _ = map( z.extend, y )
['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