0

I'm very new to this, so this might be simple.

I have a list of variables with numbers: row1, row2, row3, etc.

Can I loop through them to check if they match another value?

row1 = "a"
row2 = "b"
row3 = "c"

for i in range(1, 3):
    if row + str(i) == "c":
           print("pass")
  • Why don't you just put them in a list? – UnholySheep Dec 14 '19 at 18:40
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea Dec 14 '19 at 19:13

2 Answers2

2

There is a function eval, which lets you evaluate a string representing a Python expression:

row1 = 'a'
eval('row1') == 'a'  # True

It is, however, rarely used (Why is using 'eval' a bad practice?), and probably not what you want. You would usually store objects (like the string objects in your case) in a structure like a list or dict, and query them by index or by key:

rows = ['a','b','c']

for i in range(3):
    if rows[i] == 'c':
        print('pass')

The more Pythonic way is to loop over the iterable directly:

rows = ['a','b','c']

for row in rows:
    if row == 'c':
        print('pass')
sammy
  • 857
  • 5
  • 13
0

If you do have a need to be able to refer to the name the variable was assigned to then you would be better to use a python dictionary to store your data, you can then iterate through the keys and values

data = {
    'row1': "a",
    'row2': "b",
    'row3': "c",
    'row4': "b",
    'row5': "c"
}

for key, val in data.items():
    if val == "c":
        print(f'c was found assigned to key {key}')

OUTPUT

c was found assigned to key row3
c was found assigned to key row5
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42