Reputation: 321
I am trying to find a way to iterate over the letters of a string and return the indexes of those letters in a list, but I don't want to use loops or enumerate, the below code is a function that I wrote using enumerate. Any ideas on how we can do the same thing without loops or getting to use the enumerate function.Recursion is not allowed as well. '''
def getIndex(word):
return list(map(lambda t: t[0],enumerate(word)))
print( getIndex("banana"))
#output
#[0, 1, 2, 3, 4, 5]
'''
Upvotes: 0
Views: 64
Reputation: 2744
You can make a list
, with a range
as argument. This range
here is a range of numbers from 0 to the length of your word (when you only pass one argument into range
, like we do here, it defaults to the "stop" value, so the length to which the range will run)
def getIndex_zero(word):
return list(range(len(word)))
print(getIndex_one("Banana")) #Prints [0,1,2,3,4,5]
This code will generate your desired result.
Depending on whether or not you want to use zero based indexing, you can also use the following (To make your list start at 1)
def getIndex_one(word):
return list(range(1, len(word)+1))
print(getIndex_one("Banana")) #Prints [1,2,3,4,5,6]
Upvotes: 1