[Tutor] lists

Alan Gauld alan.gauld at yahoo.co.uk
Fri Nov 27 18:45:08 EST 2020


On 27/11/2020 19:54, Bernardo Rebelo wrote:
> Hi I would like to know how to check if an element in a list is greater
> than the next element on the same list like this
> 
> [5,4,3,2,1]
> 
> if 5 > 4 > 3 > 2 > 1
> return True
> 
> in an example like this one [5,4,5,2], it would give False.

You need to write some code.

You probably want a loop that starts at the first
element and goes up the the second last comparing
each with the next in line. Or, slightly easier to
do in python, one that starts at the second element
through to the end and compares wit the previous
to see if its less. We can do that using a slice.
We don't do homework for people and I'm not sure
if this is homework or not, so just in case here
is some psuedo code:

>>> l1 = [5,4,3,2,1]
>>> l2 = [5,4,5,3,1]

>>> def check(L):
	for index,item in enumerate(L[1:]):
	    check if item is less than L[index}
            if not return False
            if it is continue to the next item
        if all are ok return True

>>> check(l1)
True
>>> check(l2)
False
>>>


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list