Monday, 18 March 2019

Finding last element in array - Check if current element is last element in Python arrays

When we are using loops in Python we might fumble onto a situation where we have to check if we reached the end of the array or simply say that we are iterating through each element in array and checking if the current element exists in a hash/dictionary/database and upon a match we still want to continue until the end of the array is reached.

So there are multiple ways of achieving this but I am going to give a simple solution that is easier to understand.

for suffix in suffixes:
        if(re.search(suffix+'$', my_string)):
            #do something
        elif(suffix == suffixes[-1]):
            print("reached end of array")

So the line that checks for the last element of array is

        elif(suffix == suffixes[-1]):

Similarily, to access for last but second element use suffixes[-2] and so on.

Hope its useful.

No comments:

Post a Comment