How to increment variable names/Is this a bad idea [duplicate]

烈酒焚心 提交于 2019-11-27 15:37:51

You should append all the values to a list, that allows you to easily iterate through the values later as well as not littering your namespace with useless variables and magic.

should I be using a completely different method such as appending all the new values onto a list?

Yes, you can use a list. You can also use a mapping for this.

make variable names increment like that

No. That's a horrifyingly bad idea.


"but just out of complete curiosity, is these a way to do it in the asked manner?"

Yes, but it's clearly a horrifyingly bad idea. So, there's no point in showing it. It's a terrible, terrible thing to even attempt.

While using a list or dictionary is of course the right approach here, it is possible to create named variables, using exec(). You'll miss out on all the convenient operations that lists and dictionaries provide (think of len(), inserting, removing, sorting, and so on), but it's possible:

count = raw_input('Number of variables:')
for i in xrange(count):
    exec('var_' + str(i) + ' = ' + str(i))

exec() accepts and executes strings that contain valid Python expressions. So the above piece of code is generating and executing code on the fly.

Maybe this will help you out.

filenamee = 'Value_'
counter1 = 1
counter2 = 2
list1 = []
list2 = range(30)    #random number, given len needed
for x in list2:
    counter1 = str(counter1)
    full_name = (filenamee+counter1)
    list1.append(full_name)
    counter1 = counter2
    counter2+=1

for x in list1:
    print(x)

If you're looking to make an incremental variable, this works for me. I've got no clue whether this is clean programming or not... :)

Take care

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!