Initialize many string variables


I’m initializing a lot of string variables as follows:

a, b, c, d, e, f, g, h = "", "", "", "", "", "", "", ""

You can see that this doesn’t look very nice (morever the variables have longer names). Is there some more compact shortcut?

Asked By: xralf



Definitely more compact:

Answered By: Scott Hunter

As an alternative answer to the a=b=c=...=value solution try:

a, b, c, d, e, f, g, h = [""]*8

Though if you’re doing this, it might make sense to put the variables in a list if they have some relation to each other.

Answered By: Hooked
from collections import defaultdict

To initialize:

attrs = defaultdict(str)

To get 'a' value:

print attrs['a'] # -> ''

To change it:

attrs['a'] = 'abc'
Answered By: jfs

try this one.

a, b, c, d, e, f, g, h = ["" for i in range(8)]
Answered By: neouyghur

While many of the solutions featured here are cute, I’m going to make the case that the following is the most compact solution you should consider:

a = ""
b = ""
c = ""
d = ""
e = ""
f = ""
g = ""

These seven lines of code will be read and comprehended an order of magnitude faster than any of the other solutions. It is extremely clear that each variable is being initialized to an empty string, and your eyes can quickly comprehend this code and move on to other more important code.

And let’s be honest, with modern monitors the above code is hardly a waste of screen real estate.

If you find that you need to initialize more than 7 variables then I would suggest your design needs reconsideration. Consider replacing these variables with a more dynamic use of a dictionary or list.

Answered By: Cory Klein

I know this question is about string variables, but to save some lives, remember not to use the same syntax to initialize empty lists:

list1 = list2 = []
list1.append('some string!') # This will be added to both list1 and list2 

Lists are objects and with the above situation, both list1 and list2 will have the same reference in memory.

Answered By: EspressoCode
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.