Extend multiple elements in one line iteration

  • A+
Category:Languages

For

A=[1,2,3]

I would like to get

B=['r1','t1','r2','t2','r3','t3']

I know it is easy to get ['r1','r2','r3'] by

['r'+str(k) for k in A]

How could I get B by one line loop as I showed above?

Many thanks.

 


Use a nested list comprehension:

A=[1,2,3]  B = [prefix + str(a) for a in A for prefix in 'rt'] 

Comment

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