Python Tip #83 (of 365):

Don't overuse variables in Python.

Expressions are valid almost anywhere in Python.

If a variable name isn't needed to refer to a value multiple times AND the variable name isn't any clearer than the Python expression that produces its value, just use the expression instead.

๐Ÿงต (1/4)

#Python #DailyPythonTip

Intermediary steps CAN have their own variables:

words = sentence.split()
last_3_words_list = words[-3:]
last_3_words = " ".join(last_3_words_list)

But if the variables aren't any clearer than the expression, just use the expression:

last_3_words = " ".join(sentence.split()[-3:])

๐Ÿงต (2/4)

You might retort with "but the expression is harder to understand without the variables".

This is clearly subjective and reasonable people may disagree.

If you find one big expression harder to read, then use variables to improve readability.

But there's no reason to embrace variable minimalism OR variable maximalism.

๐Ÿงต (3/4)

Maybe this is what's most readable:

words = sentence.split()
last_3_words = " ".join(words[-3:])

Or maybe it's this:

last_3_words = " ".join(sentence.split()[-3:])

But if a variable isn't any clearer than the expression it represents, just use the expression.

๐Ÿงต (4/4)

@treyhunner Parentheses, line breaks, and comments are all tools that can be more useful than variables in this case too!