You can use the zip()
function and the all()
function:
is_ascending = all(i < j for i, j in zip(currentList[:-1], currentList[1:]))
currentList[:-1]
slices the original list so that the first slice excludes the last element. currentList[1:]
does the same, with the first element.
zip()
these two slices gives us an iterator that, when unpacked, puts element x
in the variable i
, and element x+1
in the variable j
.
Then, we simply compare i
and j
and check that the condition holds for all such pairs.
This is probably not faster than writing everything out because of the need to slice the lists, but is extendable to longer lists without having to write everything out. An alternative to slicing is iterating over the range.
is_ascending = True
for i in range(len(currentList)-1):
if currentList[i] >= currentList[i+1]:
is_ascending = False
break
To check which one is fastest, let's put all these in their own functions:
def fun1(currentList):
return (currentList[0] < currentList[1]) and (currentList[1] < currentList[2]) and (currentList[2] < currentList[3]) and (currentList[3] < currentList[4])
def fun2(currentList):
return all(i < j for i, j in zip(currentList[:-1], currentList[1:]))
def fun3(currentList):
for i in range(len(currentList)-1):
if currentList[i] >= currentList[i+1]: return False
return True
testlist = [1, 2, 3, 4, 5]
%timeit fun1(testlist)
306 ns ± 29.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit fun2(testlist)
1.15 µs ± 44.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit fun3(testlist)
741 ns ± 43.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Clearly, your original approach (fun1
) is the fastest (because it doesn't need to create any extra objects), but if you had more elements in your list it would quickly get annoying to write. This example is a good illustration of why "most pythonic" is not synonymous with "fastest".