Dynamic variable in Python [duplicate]
How can I create lists with dynamic names in python, for example
for i in range(len(myself)):
list(i) = []
what should I use instead of list(i) ? it means that i want some names as below:
list1
list2
list3
...
I'd advise you to just use a list or dictionary instead of dynamic variable names. All the versions below result in lists[0]
, lists[1]
etc being []
, which seems close enough to what you want, and will be more readable/maintainable in the long term. (Note: I'm using lists
instead of list
as a variable name because the latter would overwrite the builtin list
function, which you probably don't want).
1) Version with lists
being a list of lists (the numbers are just the order of the lists):
lists = [[] for i in range(len(myself))]
2) Same but with a for loop instead of a list comprehension:
lists = []
for i in range(len(myself)):
lists.append([])
3) Version with lists
being a dictionary of lists with numbers as keys (a bit more flexible if you want to remove some of the values later or such):
lists = {}
for i in range(len(myself)):
lists[i] = []
About dynamic variable names, i.e. variables like list1
instead of lists[1]
... Seriously, you probably shouldn't do that. It's unnecessarily complicated and hard to maintain. Think about it - next month you'll want to modify the script, and you'll try to figure out where the variable list1
was defined, and you won't be able to do that with a plain text search. It's a pain.
But if you really want to for some reason, it's possible with exec
- here are some reasons not to use it - or with modifying locals()
- bad idea according to documentation. Also see comments for more discussion on why these things are a bad idea and how confusing it gets even talking about them.
Dynamic variable names are very rarely a good idea; it is almost always better to use a dictionary:
myLists = {"list{}".format(i):[] for i in range(len_i)}
Do not use list
as a variable name - it hides the existing keyword.