0

I am newbie, apologies if I used wrong terminology
I have a ton of variables (named with strings and integers) in my code and want to make a simple loop to call all the variables easily.

Example:

acc1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
acc2 = ["John", "Doe", "Example", "code"]
c = [1, 2]

for i in c:
    something = 'acc'+str(i)
    # convert string to list
    print(something[0])

I'd like to concatenate letters in acc1 and acc2 in a loop. So that I can work on a certain variable in the loop.

I am not sure if what I did is correct. I created strings to form the variable name, which is not working out.

Any help is appreciated
Thanks

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Sree
  • 73
  • 6
  • 1
    I think this is an [XY problem](https://xyproblem.info/) - I think you are asking how to dynamically look up the symbol table to convert `"acc1"` to the variable `acc1` ([reasonably easy to do](https://stackoverflow.com/q/1373164/1270789)), but I think the problem is why do you have `acc1`, `acc2` instead of a list `acc[]` in the first place. – Ken Y-N Nov 16 '21 at 03:16
  • I referred this as an example. My original code has a different naming scheme (including strings and numbers). – Sree Nov 16 '21 at 03:18
  • Do you want to concatenate like John1, Doe2, or J1, o2, h3, n4? – qiweunvjah Nov 16 '21 at 03:20
  • @Programmer No, I want to use the loop to call the list items in individual variables – Sree Nov 16 '21 at 03:21
  • What is the expected result? – Swagrim Nov 16 '21 at 03:43
  • @Sree can you please tell me what the expected result is? – Swagrim Nov 16 '21 at 03:47
  • @Swagrim I want to create a loop to access list items in a multiple variables. – Sree Nov 16 '21 at 03:53

1 Answers1

0

If you're trying to dynamically access variables defines in your current scope, you could try using the locals() function. This will return a dictionary with the name of the variables in the current scope as the key and their value as the value of the dictionary.

acc1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
acc2 = ["John", "Doe", "Example", "code"]
c = [1, 2]

variables = locals()

for i in c:
    variable_name = "acc" + str(i)
    
    print(variables.get(variable_name))

On a side note, you might want to look into f-strings if you're using python 3.5 or greater. It's possible to simply replace the string concatenation with f"acc{i}"

Zykerd
  • 138
  • 5