1

Im new to python and I stumbled on this problem, I would like to call a specific element in an array, but the array name is controlled by another array:

array1 = ["foo","bar","fubar"]
array2 = ["array1","array3","array4"]
number = 2

inter = array2[0]
test = inter[number]
#what im trying to achieve: test = array1[2]
#expecting: fubar
#what im getting: r
print(test)

Thanks guys :)

2
  • These are python list objects. But anyway, you simply have strings in your second list. The fact that those strings happen to be the same as the variable names is nothing those lists know about. You can dynamically execute strings as code, but there is no need for that, it is a fundamentally bad design choice. Use another data structure, like a dict, if you want to map strings to other objects. Commented Oct 24, 2018 at 10:45
  • Just wondering, don't you mean to use a dict to map strings to objects? Commented Oct 24, 2018 at 10:46

2 Answers 2

3

Don't use strings but references to the arrays.

array1 = ["foo","bar","fubar"]
array2 = [array1, array3, array4] # use references instead of strings here
number = 2

inter = array2[0]
test = inter[number]
print(test)
Sign up to request clarification or add additional context in comments.

1 Comment

You answered first with better wording, I'll delete mine. Fast response!
0

What you want to do is use the array that you need not the name of the array.

To make things work you have to do like shown below. Assuming array3 and array4 are defined earlier

array1 = ["foo","bar","fubar"]
array3 = []
array4 = []
array2 = [array1,array3,array4]
number = 2

inter = array2[0]
test = inter[number]
print(test)

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.