pythonpython-3.xlistdeclaration

Is there a way to declare variables in list creation?


I'd like to create and assign new String variables when I create my list. I'd like to do something like:

l = [first = "first", second = "second"]

Is something like this possible?


Solution

  • That syntax is not allowed. Instead you can do the following (You can name it whatever you like, in-place unpacking, iterable unpacking, etc.):

    first, second = ["first", "second"]
    

    However, very similar to what you want to do you can create a dictionary as following which also seems more efficient and Pythonic for your goal here.

    In [1]: d = dict(first_k = "first", second_k = "second")
    
    In [2]: d['first_k']
    Out[2]: 'first'
    
    In [3]: d.keys()
    Out[3]: dict_keys(['first_k', 'second_k'])
    
    In [4]: d.values()
    Out[4]: dict_values(['first', 'second'])