Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More elegant way of declaring multiple variables at the same time

To declare multiple variables at the "same time" I would do:

a, b = True, False

But if I had to declare much more variables, it turns less and less elegant:

a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True ,True , True, True

Is there a better / elegant / convenient way to do this?

This must be very basic, but if I do used a list or a tuple for storing the variables, how would I have to approach so that I would be helpful since:

aList = [a,b]

Is not valid, I would have to do:

a, b = True, True

Or what am I missing?

like image 286
Trufa Avatar asked Mar 31 '11 04:03

Trufa


People also ask

How do you declare multiple variables?

Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values. If more than one variable is declared in a declaration, care must be taken that the type and initialized value of the variable are handled correctly.

How do you declare multiple variables with the same value?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

Is it possible to declare multiple types of variables?

Yes you can and it is slightly more nuanced than it seems. You can use the same syntax in function parameter declarations: func foo(a, b string) { // takes two string parameters a and b ... } Then comes the short-hand syntax for declaring and assigning a variable at the same time.

Can we declare more than one variable at a time?

Declaring multiple variables in a single declaration could cause confusion about the types of variables and their initial values. In particular, do not declare any of the following in a single declaration: Variables of different types.


2 Answers

a, b, c, d, e, g, h, i, j = (True,)*9
f = False
like image 64
Shariq Avatar answered Oct 19 '22 10:10

Shariq


Use a list/dictionary or define your own class to encapsulate the stuff you're defining, but if you need all those variables you can do:

a = b = c = d = e = g = h = i = j = True
f = False
like image 39
yan Avatar answered Oct 19 '22 09:10

yan