Exercise 72

Write a function which takes an element x and a list L as a parameter, and returns the list of positions of x in L. The function must return the empty list if the element x does not appear in the list L.

Solution

def positions (x, L):
# initialization of the list of positions of x in L
LPositions = []

for i in range (0, len (L)):
if L [i] == x:
LPositions.append (i)
return LPositions
#Example
x = 3
y = 5
L = [2, 3, 7, 3, 11, 9, 3, 4]
print (positions (x, L)) # the output [1, 3, 6]
print (positions (y, L)) # the output: []
Younes Derfoufi
my-courses.net

Leave a Reply