it-Python-courses-python-string--Python-courses-python-exercises

Exercise 53

Write an algorithm in Python allowing to determine the penultimate index of an element in a list without using any predefined function in Python. Example if L = [2, 7, 11, 7, 21, 39, 7] and a = 7 the algorithm returns 3.

Solution

# function which determines the penultimate index of an element in a list
def penultimate (L, a):
# initialization of the index list
lIndex = []
for i in range (0, len (L)):
if L [i] == a:
lIndex.append (i)
return lIndex [len (lIndex) - 2 ]

# Example
L = [2, 7, 11, 7, 21, 39, 7]
a = 7
print (penultimate (L, a)) # the output: 3
Younes Derfoufi
my-courses.net

Leave a Reply