Consider this code:
def function(condition):
if condition == 'condition1':
print('No problem here')
if condition == 'condition2':
test = ['1','2','3','4']
print(test)
if condition == 'condition3':
#doing something else using variable 'test'
Is it possible to share the static list between the two if
statements? For the moment, I have two working ideas but both has its limitations
Case 1: Declare the static list at the beginning of the function
def function(condition):
test = ['1','2','3','4']
if condition == 'condition1':
print('No problem here')
if condition == 'condition2':
print(test)
if condition == 'condition3':
#doing something else using variable 'test'
Limitations: This means I will create the list every time I call function
, even though I don't need it when condition == 'condition1'
Case 2: Declare the static list in both if statement
def function(condition):
if condition == 'condition1':
print('No problem here')
if condition == 'condition2':
test = ['1','2','3','4']
print(test)
if condition == 'condition3':
test = ['1','2','3','4']
#doing something else using variable 'test'
Limitations: In this particular case it seems not so bad, but if my list had a lot more data with nested lists, repeating it would make code maintenance a lot harder since changes would need to be done more than once.
Maybe there is an easy way out of this and I'm over thinking the whole thing, but as I said this is the first time I've seen this situation.