I have two Python modules: user.py and lib.py. lib.py contains certain functions that are written in the following way and are called from the user.py module:
def foo1():
pass
def foo2():
pass
def foo3():
pass
Now I want to add a static list of strings in the lib.py module such that all the functions in lib.py module can use them. I want to strictly initialize the string list in the following way:
string_list = []
string_list.append('string1')
string_list.append('string2')
string_list.append('string3')
string_list.append('string4')
What is the most Pythonic way to achieve this? Would it be possible to do something like this that would work just fine?
string_list = []
string_list.append('string1')
string_list.append('string2')
string_list.append('string3')
string_list.append('string4')
def foo1():
print string_list[0]
def foo2():
print string_list[1]
def foo3():
print string_list[2]
Just use a Python list literal:
string_list = ['string1', 'string2', 'string3', 'string4']
No need to call list.append()
4 times if all you are doing is create list of predetermined size and contents.
In this case, you can also use composition ...
stringList = ['string'+str(i+1) for i in range(4)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With