Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python create a new list by successvely repeating the existing string elements

Tags:

python

list

I have a list. I want to repeat the elements by adding a common to each of them.

main_list = ['lst1','lst2','lst3']  # existing list

new_list = ['lst1_mean','lst1_std','lst2_mean','lst2_std','lst3_mean','lst3_std']  # expected list

My code:

aux_list1 = [i+'_mean' for i in main_list]
aux_list2 = [i+'_std' for i in main_list]
new_list = [i,j for i,j in zip(aux_list1,aux_list2)]

Is there a better way of doing it?

like image 213
Mainland Avatar asked Jun 18 '26 08:06

Mainland


1 Answers

You can simply use a nested loop:

main_list = ['lst1', 'lst2', 'lst3']
suffixes = ['_mean', '_std']

new_list = [w + s for w in main_list for s in suffixes]

print(new_list)

Output:

['lst1_mean', 'lst1_std', 'lst2_mean', 'lst2_std', 'lst3_mean', 'lst3_std']

You can also use itertools.product (which has the concept of having a variably deep nested loop):

from itertools import product

main_list = ['lst1', 'lst2', 'lst3']
suffixes = ['_mean', '_std']

new_list = [''.join(w) for w in product(main_list, suffixes)]

print(new_list)

Output:

['lst1_mean', 'lst1_std', 'lst2_mean', 'lst2_std', 'lst3_mean', 'lst3_std']
like image 126
MrGeek Avatar answered Jun 20 '26 22:06

MrGeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!