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?

5
  • What issues are you having? Commented Mar 26, 2014 at 18:44
  • why don't you use a list with all filenames? Commented Mar 26, 2014 at 18:45
  • 2
    why not use a dictionary for this?? Commented Mar 26, 2014 at 18:45
  • just use a list and append, look here Commented Mar 26, 2014 at 18:46
  • okay so I don't know how to use a dictionary and Ruben bermudez I want it to work wnatever the range is so if its 10 then it does ten variables but if its 20 it does 20 a so on so fourth Commented Mar 26, 2014 at 18:48

4 Answers 4

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"]
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

generally speaking this is a bad idea ... I think
@Joran Beasley much agreed.
@Joran Beasley however, it does directly answers op's question
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

Comments

-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)

3 Comments

No. He merely needs to change range(10) into something like range(1,11) instead.
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?"
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 you will be able to comment on any post.

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.