Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over each string in a list of strings and operate on it's elements

Im new to python and i need some help with this.

TASK : 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.

Given list is :

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh'] 

If i try 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 

please let me know, how would i achieve comparing the first and the last element of a no. strings in the list.

Thanks in advance.

like image 434
user3168141 Avatar asked Jan 07 '14 10:01

user3168141


People also ask

How can you use a loop to iterate over a list of elements?

We often want to perform the same operation on every element in a list, like displaying each element or manipulating them mathematically. To do that, we can use a loop to iterate over each element, repeating the same code for each element.


2 Answers

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]) 
like image 130
Steinar Lima Avatar answered Sep 21 '22 19:09

Steinar Lima


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.

like image 26
ShinTakezou Avatar answered Sep 23 '22 19:09

ShinTakezou