3

How can I go about checking if an element comes before another in a list?

For example:

how can I check if 5 comes before 12 in a list:

li = [1,2,3,7,4,5,10,8,9,12,11]

Is there an built-in Python function that can allow me to do that?

user2891763
  • 413
  • 3
  • 7
  • 12

4 Answers4

6

Here ya go:

>>> li = [1,2,3,7,4,5,10,8,9,12,11]
>>> li.index(5) > li.index(12)    # 5 comes after 12
False
>>> li.index(5) < li.index(12)    # 5 comes before 12
True
>>>
>>> help(list.index)
Help on method_descriptor:

index(...)
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

>>>
3
if li.index(5) < li.index(12):
   print "came before"
jramirez
  • 8,537
  • 7
  • 33
  • 46
0

You can use list's inbuilt index function:

>>> l = [1,2,3,7,3,5,21,8,44,16,12]
>>> l.index(5) > l.index(12)
False
>>> l.index(5) < l.index(12)
True
>>>

index returns the index of the first occurrence of a number. An example of how index works:

>>> t = (0,1,2,3,4,0,1,2)
>>> t.index(3)
3
>>> t.index(0)
0

Note that there are two 0s here.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
-3

I don't know python, but generally arrays and lists in programming languages use a zero-based index to identify each element. You usually can access each element via their index in the using the format li[index] = element. For example:

let li = [1,2,3,7,4,5,10,8,9,12,11]

li[0] = 1;
li[1] = 2;
li[2] = 3;
li[3] = 7;
li[4] = 4;

etc. Many systems will also have an IndexOf() method that will allow you to determine the index of an element using a format similar to li.IndexOf(element). This feature can be used in your example such as:

Boolean Is_5_B4_12 = li.IndexOf(5) < li.IndexOf(12);

If python does not have such a feature, you can easily create one yourself by using a loop and an incrementor. Something similar to this would work:

Function IndexOf(integer element)
    integer index = 0;
    Do While index < len(li) //len() is a function that specifies the number of elements in the list
        if li[index] == element then return index;
        index = index + 1;
    Loop
End Function

I hope this answers your question! Regards - yisrael lax

ylax
  • 376
  • 4
  • 8