1

I want to dynamically name the list and use that,I searched a lot but did not get the satisfactory answers how to do that.

if __name__=="__main__":

    lst_2017=[]
    lst_2018=[]
    lst_2019=[]


    for year in range(2017,2020):
        #avg_data is function which returns a list of number
        lst_"{}".format(year) = avg_data() 

Error:

 File "<ipython-input-84-4c1fefedd83e>", line 9
    lst_"{}".format(year) = avg_data()
           ^
 SyntaxError: invalid syntax

Expected :

loop will iterate 3 times and function return the 3 list in the respective lists

example:

 lst_2017=[1,2,4]
 lst_2018=[3,4,5]
 lst_2019=[3,4,6]
1
  • 1
    There's no need to create dynamically named variables. It is not useful. Consider using a dictionary instead. Commented May 16, 2020 at 20:06

2 Answers 2

4

Use a dictionary instead of naming multiple dynamic variables. Then all your data is in one data structure and easily accessible from key/value pairs.

For the below example I simply zip up the years and data together to construct a dictionary, where years are the keys and averages are the values.

avg_data = [[1,2,4], [3,4,5], [3,4,6]]

result = {}
for year, avg in zip(range(2017, 2020), avg_data):
    result[year] = avg

print(result)

Which can also be done like this, since zip(range(2017, 2020), avg_data) will give us (year, avg) tuples, which can be directly translated to our desired dictionary using dict():

result = dict(zip(range(2017, 2020), avg_data))

print(result)

Output:

{2017: [1, 2, 4], 2018: [3, 4, 5], 2019: [3, 4, 6]}

You'll probably have to tweak the above to get your desired result, but it shows the general idea.

Sign up to request clarification or add additional context in comments.

Comments

2

Use dictionary with iter:

avg_data = [[1,2,4], [3,4,5], [3,4,6]] 
it=iter(avg_data)
d={}
for i in range(2017,2020):
    d["lst_"+str(i)]=next(it,None)

for k in d.keys():
    print(k, "=",d[k])

Comments

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.