Interleave a list with a modified version of itself

  • A+
Category:Languages

Suppose I have a list:

l=['a','b','c'] 

I'd like the desired output to be:

out_l = ['a','a_1','b','b_2','c','c_3'] 

I can write regular for loop to get this done, but I'm wondering if there's a more Pythonic way (e.g., using list comprehension or lambda) to get it done.

I've tried something like this:

list(map(lambda x: x[1]+'_'+str(x[0]+1), enumerate(a))) # this only returns ['a_1', 'b_2', 'c_3'] 


You can use a list comprehension like so:

l=['a','b','c'] new_l = [i for b in [[a, '{}_{}'.format(a, i)] for i, a in enumerate(l, start=1)] for i in b] 

Output:

['a', 'a_1', 'b', 'b_2', 'c', 'c_3'] 

Optional, shorter method:

[j for i, a in enumerate(l, 1) for j in [a, '{}_{}'.format(a, i)]] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: