How to iterate over each string in a list of strings and operate on it's elements
Try:
for word in words:
if word[0] == word[-1]:
c += 1
print c
for word in words
returns the items of words
, not the index. If you need the index sometime, try using enumerate
:
for idx, word in enumerate(words):
print idx, word
would output
0, 'aba'
1, 'xyz'
etc.
The -1
in word[-1]
above is Python's way of saying "the last element". word[-2]
would give you the second last element, and so on.
You can also use a generator to achieve this.
c = sum(1 for word in words if word[0] == word[-1])
The reason is that in your second example i
is the word itself, not the index of the word. So
for w1 in words:
if w1[0] == w1[len(w1) - 1]:
c += 1
print c
would the equivalent of your code.