0

I have this code

for i in range(10):
    variablename = "file" + str(i)

and I want to be able to go generate variables depending on the i variable like if range was to 10 would have variables like this

  • file1
  • file2
  • file3
  • file4
  • file5
  • file6
  • file7
  • file8
  • file9
  • file10

How would I do this?

WGS
  • 13,969
  • 4
  • 48
  • 51

4 Answers4

4

You can use a Dictionary

dict = {}
for i in range(10):
    dict["file" + str(i)] = "value for this var"

then you can obtain a value using the variable name

f1 = dict["file1"]
1

you could use globals() function which contains a dictionary of all the global variables. To which I recommend reading these two pages if you are unfamiliar with scope, or dictionaries

http://docs.python.org/2/library/stdtypes.html#typesmapping

Short Description of the Scoping Rules?

for i in range(10):
    globals()["file" + str(i)] = "newvarvalue!" + str(i)
print file0
print file1
print file2
print file3
print file4
print file5
print file6
print file7
print file8
print file9

EDIT removed locals() from solution

Community
  • 1
  • 1
flakes
  • 21,558
  • 8
  • 41
  • 88
0

list comprehensions

filenames = ["file%d.txt"%i for i in range(1,11)]

or if you want them as variable names store them in a dictionary as suggested in P0lyb1us's Answer

Community
  • 1
  • 1
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
-4

You you need to give range() two arguments for it to work so you should change your code to:

for i in range(1,11):
     variablename = "file" + str(i)
cheese12345
  • 573
  • 1
  • 5
  • 15
  • No. He merely needs to change `range(10)` into something like `range(1,11)` instead. – WGS Mar 26 '14 at 18:49
  • 2
    I don't think the question is "why am I getting file0 instead of file1 as my first element?" but rather, "how do I take this string, and make it be the name of a variable?" – Kevin Mar 26 '14 at 18:50
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). – Ansgar Wiechers Mar 26 '14 at 19:28