0

I want to do something like this in Python, I want to use a string from a list or tuple and use it as a variable.

points = ['p1', 'p2', 'p3']
points(0) = input('insert number')
points(1) = input('insert number')
points(3) = input('insert number')

I tried something like this

points = []
i = 0
n = int(input('inser number of points '))
while i < n:
    points.append(str(input('insert.. ')))
    i = i+1
points(0) = input('insert number')
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 2
    You may want to provide the language you're using and to review the guidelines on how to ask a question. [ask] – Reeza Nov 25 '20 at 22:09
  • Did you try putting something like `how do I put a value into a list in python` into a search engine? – Karl Knechtel Nov 26 '20 at 08:34

2 Answers2

1

In python the array is accessed using [ ]. Beyond that you cannot assign values to indices outside what you have already declared. You gave declared a list if size 3 therefore the last one which accesses 30 will throw an exception complaining about out of index error. If you need an array of a given size you may declare one

my_list = [None]*size
flutterby
  • 46
  • 1
  • 6
0

I do not understand clearly your question, if you are trying to create variables inside a loop, be careful. You will have to declare the variables as global(), If I remember correctly, it is not the best practice, it is always better to define variables OUTSIDE the loop. Going back to your question, I think the best approach here would be to use PYTHON DICTIONARIES, creating the 'variables' as dictionary keys and then create the data of each variable on another loop.

n = int(input('inser number of points '))
ListOfVariables=[]
for i in np.arange(0,n):
    ListOfVariables.append('point'+str(i))

DictionaryWithVariables=dict.fromkeys(ListOfVariables)

Then, each time you want to set a value inside the variable, you just have to access it inside the dictionary:

DictionaryWithVariables["point1"]=10.0