Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to initialize a static list in a Python module

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]
like image 887
Rafay Avatar asked Dec 26 '22 11:12

Rafay


2 Answers

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.

like image 130
Martijn Pieters Avatar answered Jan 06 '23 04:01

Martijn Pieters


In this case, you can also use composition ...

stringList = ['string'+str(i+1) for i in range(4)]
like image 23
ssm Avatar answered Jan 06 '23 04:01

ssm