# To output a list of Python recursive function utilization index values

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

The code I made is

``````listn=[] #emptylist
def searchn(list, key): #searchn function definition

for n in range (len(list)):
if list[n]==key:
listn.append(n)
print(listn)
``````

Like this, let the for statement rotate by Len of the list valueWell. The [n] value of the list (index value) is stored in the new list, listn.

How can I express this as a recursive function?

python list recursive

2022-09-20 10:48

``````>>> l = [ 1, 2, 3, 4, 5 ]
>>> def searchn(l, k, offset=0):
if len(l) == 1:
ilist = []
if l == k:
ilist.append(0+offset)
return ilist
if l == k:
return [ offset ] + searchn(l[1:], k, offset+1)
return searchn(l[1:], k, offset+1)

>>> searchn(l, 3)

>>> l = l+l+l
>>> searchn(l, 3)
[2, 7, 12]
>>> def searchn(l, k, offset=0):
if len(l) == 0:
return []
if l == k:
return [ offset ] + searchn(l[1:], k, offset+1)
return searchn(l[1:], k, offset+1)

>>> searchn(l, 3)
[2, 7, 12]
>>> searchn([1,3,3,3,3], 3)
[1, 2, 3, 4]
``````

2022-09-20 10:48

## If you have any answers or tips

Popular Tags
python x 4520
android x 1589
java x 1455
javascript x 1363
c x 881
php x 682
html x 629
swift x 586
ios x 538
mysql x 397