I know Python is a dynamic language and declaring variables before-hand is generally not necessary, but in the case where I need to create a variable and then give it a value later, both of the following methods work:
some_variable = ''
some_variable = str()
Is there a difference between both of these and which is considered best practice?
Example:
some_variable = str()
for number in range(10):
some_variable += str(number)
print(some_variable)
Works for both some_variable = ''
and some_variable = str()
By best practice I do not mean "which is best coding style/most readable" but rather factors such as memory consumption, speed and which on the whole is more reliable for general use.
If you want to initialize a variable to an empty value, using an empty value literal will be slightly faster, since it avoids having to do a name lookup.
That is, if you write:
some_variable = str()
Python first needs to make sure you haven't written something silly like
str = int
in some visible scope first, so it has to do a recursive name lookup.
But if you write:
some_variable = ''
Then there's no way that ''
will ever be anything but a str
. (Similar principles apply for list and tuple literals: prefer []
and ()
over list()
and tuple()
.)
More generally, though: initializing a variable to an empty value is generally considered a code smell in Python. For things like an empty list, consider using a generator expression (... for ... in ...)
or a generator function (using yield
) instead -- in most cases you can avoid setting up empty values at all, and that's generally considered a more Pythonic style.