0

I have 8 lists that have a bunch of data in them named erik1,erik2,...,erik8. The code I have is:

while (y<9):#go through all the arrays
    y=y+1
    array="erik"+str(y)
    print (array)


    for z in array:

In the for loop, I want array to correspond to the string that is generated in the while loop above it. Right now it thinks of array as a string rather than the list object I want. How can i make this work?

1
  • 6
    Don't do that. Make a list of lists instead. Commented May 20, 2015 at 19:03

4 Answers 4

2

Variable names are code, not data. Use a list of lists instead.

eriks = [erik1, erik2, erik3, erik4, erik5, erik6, erik7, erik8]
for erik in eriks:
    for z in erik:
     ....

Taking a step back, whatever is creating the 8 similarly named lists should be creating a single list of lists (or a dictionary of lists) in the first place.

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

Comments

0

@chepner's answer is the correct way to go; you really should make the erik* lists a list of list. It's much more flexible that way.

However, if you can't do that for some reason (e.g. legacy code that would break if you do that), then the answer is using globals() and locals(). These two functions return dictionaries that allow you to query for objects (variables, functions, etc.) by their names.

http://www.diveintopython.net/html_processing/locals_and_globals.html

Assuming that your erik* lists are local variables (if they are global variables, use globals() instead), you can access them as followed:

for i in range(1, 9):
    array = locals()["erik"+str(i)]
    print array

Comments

0

So erik1, erik2 ... are lists referenced by the string you create in the while loop?

In this case, just use eval("erik"+str(y)) to get the list referenced by that string

[z <<DO WHATEVER YOU WANT WITH z HERE>> for z in [array for array in [eval("erik"+str(y)) for y in range(9)]]]

or

for array in [eval("erik"+str(y)) for y in range(9)]:
    for z in array:
         # DO WHATEVER YOU WANT WITH z

4 Comments

That still keeps the "["erik"+str(y) for y in range(9)]]" part as a string not as the actual list
So you want this list "["erik"+str(y) for y in range(9)]]" to be a string?
No i want it to be a list right now it is being stored as a string so it is essentially doing: for z in "erik1" rather than for z in erik1
sorry if this is confusing but erik1 - erik 8 are lists that contain data. I want to reference each list individually in a loop to read the data in each list. Doing what you suggested just puts the the string erik1 into a list like [e,r,i,k,1].
0
array = ["erik{}".format(i) for i in range(1,9)]
print array 

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.