yalpsid eman
yalpsid eman

Reputation: 3432

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?

Upvotes: 1

Views: 5206

Answers (3)

myAnnieIsDog
myAnnieIsDog

Reputation: 1

I was able to accomplish this today using the walrus operator to define variables (I was defining constants) with a list or tuple definition.

my_vars = [var1 := 3/2, var2 := 2 * var1]

MY_CONSTANTS = (CONST_A := 3/2, CONST_B := 2 * CONST_A)

Using this approach I am able to print each value.

print(my_vars, var1, var_2)

print(MY_CONSTANTS, CONST_A, CONST_B)

I did not find a way to print the variable names the way you could with a dictionary or named tuple, so in most use cases they would be a better approach. In my use case I only wanted to iterate over the variables:

for i in my_vars:
    print(i)
  
for j in MY_CONSTANTS:
    print(j)

Upvotes: 0

pirateofebay
pirateofebay

Reputation: 1090

While the syntax above is impossible, you can simply split up the variable assignment and list creation.

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

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

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'])

Upvotes: 5

Related Questions