list - Dynamic variable in Python -


this question has answer here:

how can create lists dynamic names in python, example

for in range(len(myself)):    list(i) = [] 

what should use instead of list(i) ? means want names below:

list1 list2 list3 ... 

i'd advise just use list or dictionary instead of dynamic variable names. versions below result in lists[0], lists[1] etc being [], seems close enough want, , more readable/maintainable in long term. (note: i'm using lists instead of list variable name because latter overwrite builtin list function, don't want).

1) version lists being list of lists (the numbers order of lists):

lists = [[] in range(len(myself))] 

2) same loop instead of list comprehension:

lists = [] in range(len(myself)):    lists.append([]) 

3) version lists being dictionary of lists numbers keys (a bit more flexible if want remove of values later or such):

lists = {} in range(len(myself)):    lists[i] = [] 

about dynamic variable names, i.e. variables list1 instead of lists[1]... seriously, you shouldn't that. it's unnecessarily complicated , hard maintain. think - next month you'll want modify script, , you'll try figure out variable list1 defined, , won't able plain text search. it's pain.
if want reason, it's possible exec - here reasons not use it - or modifying locals() - bad idea according documentation. see comments more discussion on why these things bad idea , how confusing gets talking them.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -