Python-courses-python-exercises-python--Python-courses-configure script-run-script

Exercise 24

Write a Python algorithm as a function which takes as parameter a couple (L, a) formed by a list L and an element 'a' and which returns the position of the element 'a' in the list L without using the index() method or any other built-in Python method. The function should return -1 if element 'a' is not present in the list L.

Solution

# coding: utf-8
def indexElement (L, a):
# initialization of the index of a
index = -1
for i in range (0, len (L)):
if L [i] == a:
index = i
break
return index

# Example
L = [2, 11, 7, 4, 3, 7, 13]
print ("the index of a in L is:", indexElement (L, 7)) # print: the index of a in L is: 2
print ("the index of a in L is:", indexElement (L, 5)) # print: the index of a in L is: -1

Younes Derfoufi
my-courses.net

Leave a Reply