Given a list:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
I need to compare the first and the last element of each string in the list. If the first and the last element in the string is the same, then increment the count.
If I try it manually, I can iterate over each element of the strings in the list:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
w1 = words[0]
print w1
aba
for i in w1:
print i
a
b
a
if w1[0] == w1[len(w1) - 1]:
c += 1
print c
1
But, when I try to iterate over all the elements of all the strings in the list , using a for
loop, I get an error.
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in words:
w1 = words[i]
if w1[0] == w1[len(w1) - 1]:
c += 1
print c
ERROR:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str
How would I achieve comparing the first and the last element of a list of strings?