Home > Net >  can python make variables itself?
can python make variables itself?

Time:10-23

Can python make variables itself ? I have to do some program that needs too many variables. So like can it do it is self ? Example :

`x= 10

#and here i need to make for example x1 but i dont want to type it

x1 = 10 

`

CodePudding user response:

hi there are a lot of options but like chepner says every would be larger than writing variable names.

if you have only numeric you can use a list:

x = [10,11,12,13,14]

then your variables will be x[0] x[1] x[2] ...

If you want to identify every variable with a name you can use a dict. supose that you want to create 10 variables with names x1,x2,... x10

my_dict = {}
for i in range(10):
    my_dict[f'x{i}'] = 10

then accessing via my_dict['x1'] , my_dict['x2']

  • Related