This question already has an answer here:
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 usinglists
instead oflist
as a variable name because the latter would overwrite the builtinlist
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):2) Same but with a for loop instead of a list comprehension:
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):About dynamic variable names, i.e. variables like
list1
instead oflists[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 variablelist1
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 modifyinglocals()
- 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:
Do not use
list
as a variable name - it hides the existing keyword.