Is it better to declare a variable in python as None if you need to assign it later inside a different local area? I could not find the best practice on this:
Appreciate your advice!
def get_executed_list(list_of_strings):
"""list_of_strings is a list"""
updated_list = None
for single_string in list_of_strings:
single_string += "-executed"
updated_list.append(single_string)
return updated_list
OR
def get_executed_list(list_of_strings):
"""list_of_strings is a list"""
updated_list = []
for single_string in list_of_strings:
single_string += "-executed"
updated_list.append(single_string)
return updated_list
OR
def get_executed_list(list_of_strings):
"""list_of_strings is a list"""
updated_list = ""
for single_string in list_of_strings:
single_string += "-executed"
updated_list.append(single_string)
return updated_list
As pointed out, only your second example actually works.
As for the question itself, I would only initialise a value to None
, for then to later reinitialise it to the intended data type, if you actually need to distinguish between the two states.
An example use case for this is a class that is intended to hold data read from an external source like a file. Say a text file of name/value pairs. Since the None
type in Python has an undefined value, it can be distinguished from for instance 0
, ""
or []
when these can represent valid value entries in your file. You can then check if you received your data and it was empty, or it was never seen at all.