[Tutor] Long Lines techniques
Steven D'Aprano
steve at pearwood.info
Fri Dec 14 00:17:12 EST 2018
On Fri, Dec 14, 2018 at 01:03:55AM +0000, Alan Gauld via Tutor wrote:
> I'd probably suggest
>
> stgs = ''.join([
> "long string",
> "another string",
> ...
> "last string"
> ])
That's certainly better than using the + operator, as that will be quite
inefficient for large numbers of strings. But it still does unnecessary
work at runtime that could be done at compile time.
Hence my preferred solution is implicit string concatenation:
stgs = ("long string"
"another string"
"last string")
Note the lack of commas.
[...]
> > or even generator expression.
>
> These are usually just parens in a function. The generator
> expression is the bit inside (not including) the parens.
Hmmm, well, yes, no, maybe. The definition of a generator comprehension
*requires* it to be surrounded by parentheses. You cannot write this:
gen = x + 1 for x in items
you must use brackets of some form:
- [] for a list comprehension;
- () for a generator comprehension;
- {} for a dict or set comprehension;
But for the generator case, a short-cut is allowed. If the expression is
already surrounded by parens, as in a one-argument function call, you
can forego the inner brackets. So instead of:
flag = any((condition(x) for x in items))
we can just write:
flag = any(condition(x) for x in items)
--
Steve
More information about the Tutor
mailing list