Create a list by concatenating a given list which range goes from 1 to n


This program creates a new list by combining elements from the list "ch" with the numbers 1 to n (inclusive) using a nested list comprehension. The outer list comprehension iterates over the numbers from 1 to n (inclusive) and the inner list comprehension iterates over the elements of the list "ch".

For each combination of elements, the program uses string formatting to create a new string in the format of "{element from ch}{number from 1 to n}". These new strings are then added to the new list. Finally, it prints the new list which is ['T1', 'J1', 'T2', 'J2', 'T3', 'J3', 'T4', 'J4', 'T5', 'J5', 'T6', 'J6', 'T7', 'J7', 'T8', 'J8', 'T9', 'J9', 'T10', 'J10']

Source Code

ch = ['T', 'J']
n = 10
new_list = ['{}{}'.format(a, b) for b in range(1, n+1) for a in ch]
print(new_list)
 

Output

['T1', 'J1', 'T2', 'J2', 'T3', 'J3', 'T4', 'J4', 'T5', 'J5', 'T6', 'J6', 'T7', 'J7', 'T8', 'J8', 'T9', 'J9', 'T10', 'J10']

Example Programs