Reputation: 29
def superindex(string, word):
return [i for i, ltr in enumerate(string) if ltr == word]
I'm a beginner with Python and I would like to know how this look works.
i for i
do?Upvotes: 0
Views: 171
Reputation: 183
It returns the indices where the letter word
matches a character in the string
variable.
for i, ltr in enumerate(string)
is a for loop over the letters in string
, because you're using enumerate you also get an index i
as well. However adding the if condition on the end means you only return i
when the letter ltr
equals the letter word
So this
string = "yuppers"
word = "p"
print(superindex(string, word))
will return this
[2,3]
Upvotes: 3
Reputation: 775
This function is creating a list of the ltr
indexes of an iterable variable string
, that match the object word
This function can be written in a simpler way:
def superindex(string, word):
l = list()
for i, ltr in enumerate(string):
if ltr == word: # check if ltr is equal to the variable word
l.append(i) # append the index i of the matching ltr in the string
return l
enumerate
[i for i...
for
loop is written as a pythonic list comprehension. This allows us to loop over an iterable and create a list in one line of code (e.g. [i for i in string]
). There are many cases where this form of a list is more efficient (see Are list-comprehensions and functional functions faster than "for loops"?)
This function will work on letters:
superindex('foo', 'o')
returns [1,2]
and also lists of words:
superindex(['foo', 'bar'], 'bar')
returns [1]
Note: Although the variables suggest this is applicable to string and words, a more appropriate naming might be (list_of_strings
and word
) or (string
and letter
). If a more general case was sought maybe (iterable
and template
)...
Upvotes: 0
Reputation: 771
The easy way to understand single-line for loop is using more basic things:
>>> l = ["a", "b", "c"]
>>> [ltr for ltr in l]
['a', 'b', 'c']
For your first question, using square brackets creates a list and it appends the ltr
value to the list by iterating over the list l
.
The enumerate
is a built-in function which allows having a counter while looping over an iterable object. Here, i
iterates over indexes of the list while ltr
iterates over the elements of the list l
. Here is another example:
>>> [i for i, ltr in enumerate(l)]
[0, 1, 2]
>>> [ltr for i, ltr in enumerate(l)]
['a', 'b', 'c']
Additioanlly, you have a condition at the end:
>>>[ltr for i, ltr in enumerate(l) if i>0]
['b', 'c']
Here, it only takes the elements of the list l
with indexes greater than 0
.
I hope, this helps understanding the concepts :)
Upvotes: 0
Reputation: 814
Would be much easier for you to under stand if it was written like this :
lst = []
for i, ltr in enumerate(string):
if (ltr == word):
lst.append(i)
Upvotes: 1