1

How can I make multiple lists based on the elements in one existing list? Names and elements of these new lists are both determined by the existing list.

For example, the existing list is:

a = [2,5,4]

The desired output is:

a_2= ['01','02']
a_5= ['01','02','03','04','05']
a_4= ['01','02','03','04']

I am not sure how to loop to create different list names. Any ideas?

3
  • A dictionary could work since I can convert the keys to list names later. Commented Aug 30, 2020 at 8:14
  • Is the 0 in the first position always required? Even for two-digit numbers? Also, do not create multiple variables. Use a list of lists or a dictionary of ists. Commented Aug 30, 2020 at 8:15
  • All strings would be 2-digits so 0 will in the first position for one-digit number. Commented Aug 30, 2020 at 8:20

3 Answers 3

1

directly defining new variables dynamically is possible but not very pythonic... my suggestion is to build a dictionary called res:

a = [2, 5, 4]

res = {n: [f"{i:02d}" for i in range(1, n + 1)] for n in a}

print(res)     # {2: ['01', '02'], 5: ['01', '02', '03', '04', '05'], 4: ['01', '02', '03', '04']}
print(res[5])  # ['01', '02', '03', '04', '05']

(where res[5] serves as your a_5)...


the messy version that dynamically adds the variables to your global namespace is:

a = [2, 5, 4]

for n in a:
    globals()[f"a_{n}"] = [f"{i:02d}" for i in range(1, n + 1)]

print(a_2)  # ['01', '02']
print(a_4)  # ['01', '02', '03', '04']
print(a_5)  # ['01', '02', '03', '04', '05']
Sign up to request clarification or add additional context in comments.

Comments

1

You can populate a dictionary with keys based on your desired variables:

a = [2, 5, 4]
output = {f"a_{i}": ["{:02d}".format(x) for x in range(1, i + 1)] for i in a}

And then you can access them easily:

print(output["a_4"]) # ['01', '02', '03', '04']

Comments

0

Does this answer you question?

a = [2,5,4]
a_2, a_5, a_4 = [['0'+str(x) for x in range(b)] for b in a]

2 Comments

Your solution will not work of a has a different number of items. Also, the first element in each of your lists is '00', not '01'.
Thank you. I tried this way before. The problem is that I would need to manually name a_2, a_5, and a_4. Is there a way that these list names (a_2, a_5, a_4) could be created by coding?

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.