generating unique variable name via loops
Peter Otten
__peter__ at web.de
Tue Nov 4 08:09:42 EST 2014
Fatih Güven wrote:
> I want to generate a unique variable name for list using python.
>
> list1=...
> list2=...
> .
> .
> .
> listx=... where x is a number.
>
> You can remember it from saving a file in a directory. If you have already
> created a "new file", save dialog sugget that <<"new file " is already
> exist, do you want to save it as "new file (1)"?>> so I want to apply it
> for list names.
>
> Do you any idea about this.
Do you really want to use
list1, list2, list3, ... as variable names? You shouldn't. Instead use a
dict or a list of lists:
>>> list_of_lists = []
>>> list_of_lists.append([1, 2, 3])
>>> list_of_lists.append(["a", "b", "c"])
>>> list_of_lists.append(["foo", "bar", "baz"])
You can then access the second list with
>>> letters = list_of_lists[1]
>>> print(letters)
['a', 'b', 'c']
On the other hand if you just want to generate names an easy to understand
approach is to increment a global variable every time you invoke the name-
generating function:
>>> _index = 1
>>> def next_name():
... global _index
... name = "list{}".format(_index)
... _index += 1
... return name
...
>>> next_name()
'list1'
>>> next_name()
'list2'
>>> next_name()
'list3'
More information about the Python-list
mailing list