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?
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?
Definitely more compact:
a=b=c=d=e=f=g=h=""
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.
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.
from collections import defaultdict
To initialize:
attrs = defaultdict(str)
To get 'a'
value:
print attrs['a'] # -> ''
To change it:
attrs['a'] = 'abc'
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.
try this one.
a, b, c, d, e, f, g, h = ["" for i in range(8)]
© 2022 - 2024 — McMap. All rights reserved.
for
cycle some values will be "" and some will be filled and a tuple (a, ... h) will be appended to a list of tuples and variables should be reseted for the next round of for cycle to "" (because the old values shouldn't be mixed) – Youngmantuple(map(some_dict.get, 'abcdefgh'))
to convert to tuple. Or better yetAttr(**some_dict)
where Attr is a namedtuple. – SmithermanL = [1, None, "abc", object(), {"key": 1.0}, ['nested', 'list], MyCustomClass(), 'etc',]
it might not be useful but you can. – Smitherman