[Tutor] Help
Mark Lawrence
breamoreboy at yahoo.co.uk
Sat Mar 7 21:28:50 CET 2015
On 07/03/2015 19:04, Alan Gauld wrote:
> On 07/03/15 15:39, elie khairallah wrote:
>> hello , I would like to know if theres a way to change a variable's name
>> after every iteration for example I want to make a function that stores a
>> number in x_1 if i=1 and in x_2 if i=2.
>> To be more precise:
>> i=1
>> def f(n):
>> while i<n:
>> x_i = i**2 ##this writing is wrong I would like here
>> to have
>> x_1 or x_2 ...
>> (depending on i)
>> return (x_1,x_2,x_3 .....)
>
> Others have already suggested a list, which IMHO is the best option.
> However if for some reason the zero based index of a list is an
> issue for you then you could use your naming scheme in a
> dictionary:
>
> def f(n):
> values = {}
> root = 'x_'
> for n in range(1,n+1):
> values[root+str(n)] = n**2
> return values
>
> You can then access the values with, for example:
>
> print (values['x_2'])
>
> But unless you are reading the variable names from
> a file/network or a user then the numerical index of a
> list will usually be easier to work with.
>
>
If zero based indexing is an issue I'd just write:-
values = [None]
to start with.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list