any
can take a generator1022 suggestions outlined here:
1023 https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
1024 """
1025 if not force and len(arg) != 0 and not any([c in arg for c in ' \t\n\v"']):1026 return arg
1027 else:
1028 n_backslashes = 0
join
can take a generator2343 data = [elems[i * nrows : (i + 1) * nrows] for i in range(ncols)]
2344 colwidths = [max(map(len, d)) + pad for d in data]
2345 colwidths[-1] -= pad
2346 row_t = "".join(["{{row[{i}]: <{{w[{i}]}}}}".format(i=i) for i in range(ncols)])2347 row_t += newline
2348 lines = [
2349 row_t.format(row=row, w=colwidths)
any
can take a generator290 before = buffer.document.char_before_cursor
291 after = buffer.document.current_char
292
293 if any(294 [before == b and after == a for (b, a) in ["()", "[]", "{}", "''", '""']]
295 ):
296 buffer.delete(1)
any
can take a generator285 before = buffer.document.char_before_cursor
286 after = buffer.document.current_char
287
288 if any(289 [before == b and after == a for (b, a) in ["()", "[]", "{}", "''", '""']]
290 ):
291 buffer.delete(1)
any
can take a generator 60 while True:
61 if not os.path.isdir(_curpwd):
62 return False
63 if any([b.name == ".hg" for b in xt.scandir(_curpwd)]): 64 q.put(_curpwd)
65 break
66 else:
The built-in function being used does not require comprehension and can work directly with a generator expression.
Using a generator expression within these functions is faster than using a comprehension:
all
any
enumerate
iter
itertools.cycle
itertools.accumulate
The inbuilt functions all()
and any()
in Python also support short-circuiting (evaluation stops as soon as the overall return value of the function is known), but this behavior is lost if you use a list comprehension. This affects performance.
# Takes a very long time to run
all_evens = all([n % 2 == 0 for n in range(100000000)])
if all_evens:
print('All numbers are even!')
# No list comprehension, runs instantly as `1` is found to be not even
all_evens = all(n % 2 == 0 for n in range(100000000))
if all_evens:
print('The numbers are all even!')