0

I'm trying to create a list of strings where each element looks like "TEMP1996_U". The year (1996 in this case) comes from a list of years and the type (U in this case) comes from a list of strings. I want the list to have every combination of year and type.

To get a list with just year, I know I can do this:

years = range(1990,2000)
type_c = ["U", "R", "K", "B"]
temp_list = map('TEMP{0}'.format, years)

Can I add type_c on to this list in a similar way?

3 Answers 3

4
from itertools import product, starmap

years = range(1990, 2000)
type_c = ["U", "R", "K", "B"]
temp_list = list(starmap('TEMP{0}_{1}'.format, product(years, type_c)))
print(temp_list)

Output:

['TEMP1990_U', 'TEMP1990_R', 'TEMP1990_K', 'TEMP1990_B', 'TEMP1991_U', 'TEMP1991_R', 'TEMP1991_K', 'TEMP1991_B',
 'TEMP1992_U', 'TEMP1992_R', 'TEMP1992_K', 'TEMP1992_B', 'TEMP1993_U', 'TEMP1993_R', 'TEMP1993_K', 'TEMP1993_B',
 'TEMP1994_U', 'TEMP1994_R', 'TEMP1994_K', 'TEMP1994_B', 'TEMP1995_U', 'TEMP1995_R', 'TEMP1995_K', 'TEMP1995_B',
 'TEMP1996_U', 'TEMP1996_R', 'TEMP1996_K', 'TEMP1996_B', 'TEMP1997_U', 'TEMP1997_R', 'TEMP1997_K', 'TEMP1997_B',
 'TEMP1998_U', 'TEMP1998_R', 'TEMP1998_K', 'TEMP1998_B', 'TEMP1999_U', 'TEMP1999_R', 'TEMP1999_K', 'TEMP1999_B']
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This gives me exactly what I want.
1

You can use list comprehension for this task:

temp_list = ['TEMP{0}_{1}'.format(y, t) for y in years for t in type_c]

It's quite clear and straightforward. That's where python really shines: Simple stuff done simply!

years = range(1990,2000)
type_c = ["U", "R", "K", "B"]
temp_list = ['TEMP{0}_{1}'.format(y, t) for y in years for t in type_c]
print (temp_list)

Comments

1

A second way (in addition to Alex Hall's answer) could be the following:

years = range(1990,2000)
type_c = ["U", "R", "K", "B"]

temp_list = []
for i in years:
    for j in type_c:
        temp_list.append("TEMP%s_%s" % (i,j))

4 Comments

Honestly this is more readable than my version, I just wanted to give something similar to what OP had in the question. But I would use a list comprehension and clearer variable names.
With a list comp and f-strings this looks nicer IMO, [f'TEMP{year}_{typ}' for year in years for typ in type_c]
Totally Agree. It almost matches with mine
I agree with all these comments. I just added a second way to do the same thing as an addition to Alex Hall's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.