I want to define (create) and use different variable (using suffix) through loop (specially for loop)

461 Views Asked by At

I want to create multiple variable through for loop to further use and compare in the program.

Here is the code -

for i in range(0,len(Header_list)):
  (f'len_{i} = {len(Header_list[i]) + 2 }')
  print(len_0);print(f'len{i}')    
  for company in Donar_list:
     print(company[i],f"len_{i}")
     if len(str(company[i])) > len((f"len_{i}")) :
        (f'len_{i}') = len(str(company[i]))
        print(f"len_{i}")

But what is happening, though I managed to create variable len_0,len_1,len_2... in line-2, in line - 3 I also can print len_0..etc variable by only using print(len_0), but I can't print it the values of these by - print(f'len_{i}')

In line 5 I also can't compare with the cofition with my intension. I want it do create variable and compare it further when as it necessary, in this case under for loop.What should I do now? I am a beginner and I can do it using if statement but that wouldn't be efficient, also my intention is not to create any **data structure ** for this.

I don't know whether I could manage to deliver you what I am trying to say. Whatever I just wanna create different variable using suffix and also comprare them through for loop in THIS scenario.

3

There are 3 best solutions below

2
On

Instead of dynamically creating variables, I would HIGHLY recommend checking out dictionaries.
Dictionaries allow you to store variables with an associated key, as so:

variable_dict = dict()
for i in range(0,len(Header_list)):
  variable_dict[f'len_{i}'] = {len(Header_list[i]) + 2 }
  print(len_0)
  print(f'len{i}')
  for company in Donar_list:
     print(company[i],f"len_{i}")
     if len(str(company[i])) > len(variable_dict[f"len_{i}"]) :
        variable_dict[f'len_{i}'] = len(str(company[i]))
        print(f"len_{i}")

This allows you to access the values using the same key:

len_of_4 = variable_dict['len_4']

If you REALLY REALLY need to dynamically create variables, you could use the exec function to run strings as python code. It's important to note that the exec function is not safe in python, and could be used to run any potentially malicious code:

for i in range(0,len(Header_list)):
  exec(f'len_{i} = {len(Header_list[i]) + 2 }')
  print(len_0);print(f'len{i}')    
  for company in Donar_list:
     print(company[i],f"len_{i}")
     if exec(f"len(str(company[i])) > len(len_{i})"):
        exec(f'len_{i} = len(str(company[i]))')
        print(f"len_{i}")
2
On
Header_list=[0,1,2,3,4]
for i in range(0,5):
  exec(f'len_{i} = {Header_list[i] + 2 }')
  print(f'len{i}') 

output:

len0
len1
len2
len3
len4
0
On

In python everything is object so use current module as object and use it like this

import sys
module = sys.modules[__name__]
Header_list=[0,1,2,3,4]
len_ = len(Header_list)
for i in range(len_):
  setattr(module, f"len_{i}", Header_list[i]+2)

print(len_0)
print(len_1)