M
M
MrChen2016-12-13 16:50:37
Python
MrChen, 2016-12-13 16:50:37

How to compare each element in a Python list?

Hello! Let's say I have a python list like this:
a = [1, 2, 3]
I need to find out if each element is greater than the previous one. How can I implement this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
Leonid, 2016-12-13
@MrChen

Read help(all) or help(any)

>>> l=[1,2,3]
>>> all(l[i] < l[i+1] for i in range(len(l)-1))
True
>>> l=[3,2,1]
>>> all(l[i] < l[i+1] for i in range(len(l)-1))
False

A
aRegius, 2016-12-13
@aRegius

Hey!
If each element is greater than the previous one, you will de facto have a sorted list. Therefore, just compare your current one with the sorted one. If True - everything is fine, each element is greater than the previous one, otherwise - False :

>>> new_list = [1, 2, 3, 4, 5, 6]
>>> new_list == sorted(new_list)
True
>>> new_list = [1, 2, 3, 4, 8, 6, 5]
>>> new_list == sorted(new_list)
False

J
Jura Semenenko, 2016-12-13
@sem9ndos

In the loop, compare "a[i]" with "a[i+1]" while i is less than the length of the array - 1.
On each iteration i+1.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question