'how to make variable name dynamic

I have a text file that has data like this:

0.90
0.43
6.03
-0.43
0.9

and I want my program to read the data and store each line in a new variable where the variable name increases automatically like this:

v1 = 0.9
v2 = 0.43
v3 = 6.03
v4 = -0.43
v5 = 0.9

I have tried this but it didn't work:

s = open("Lines_only.txt", "r")
j = 1
for i in s:
    line = i.strip()
    v[j] = float(line)
    print(v[j])
    j +=1
s.close()  


Solution 1:[1]

The proper way to do it would be to use a dictionary rather than declaring variables :

s = open("Lines_only.txt", "r")
j = 1
v_dict = {}
for i in s:
    line = i.strip()
    v_dict[f"v{j}"] = float(line)
    print(v_dict[f"v{j}"] )
    j +=1
s.close() 

#Then here access to the variables using v_dict["v1"], v_dict["v2"], ... 

However, if what you want is really to declare a variable this is possible too (but you should still use the first option if possible)

s = open("Lines_only.txt", "r")
j = 1
v_dict = {}
for i in s:
    line = i.strip()
    globals()[f"v{j}"] = float(line)
    print(globals()[f"v{j}"])
    j +=1
s.close() 

#Then here access to the variables using v1,v2, ... 
sum_result = v1+v2

Solution 2:[2]

Don't. Your code should not rely on dynamically creating variables. Use a container, such as a list.

E.g. vs = [float(line) for line in s]. Now "v1" is at vs[0], "v2" is at vs[1], and so on.

Solution 3:[3]

This is exactly what lists and arrays are intended for. You can store your data in a list that you can later index at each position, as such:

s = open("Lines_only.txt", "r")
# Initialize a list
data = []
# Populate list
for line in s:
  data.append(line)
# Now you can index into the list to get your data:
print(data[0])
print(data[3])
OUTPUT: 
0.9
-0.43

Solution 4:[4]

The other answers are correct to guide you toward collections. But in those rare cases where you need to create variable names on the fly, you can use attr() for object attributes, and either locals() or globals() for accessing variables through a dictionary interface. Thus:

with open("Lines_only.txt", "r") as s:
    j = 1
    for i in s:
        line = i.strip()
        locals()[f'v{j}'] = float(line)
        j += 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 timgeb
Solution 3
Solution 4