How to iterate over each row in a list of strings and operate on elements with it

I am new to python and I need help with this.

TASK: set the list β†’ words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

I need to compare the first and last elements of each line in the list, if the first and last elements in the line are the same, then increase the counter.

This list:

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

If I try manually, I can iterate over each element of the rows 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 rows in the list using the FOR loop.

I get an error message.

 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 a comparison of the first and last element no. lines in the list.

Thanks in advance.

+17
python string list
source share
6 answers

Try:

 for word in words: if word[0] == word[-1]: c += 1 print c 

for word in words returns the elements of words , not the index. If you ever need an index, try using enumerate :

 for idx, word in enumerate(words): print idx, word 

displays

 0, 'aba' 1, 'xyz' etc. 

-1 in word[-1] above is the Python method saying "last element". word[-2] will provide you with the second last element, etc.

You can also use a generator to achieve this.

 c = sum(1 for word in words if word[0] == word[-1]) 
+35
source share

The reason is that in the 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 

will be the equivalent of your code.

+1
source share

The suggestion that using range(len()) is equivalent to using enumerate() is incorrect. They return the same results, but they do not match.

Using enumerate() really gives you key / value pairs. Using range(len()) does not work.

First check range(len()) (working from the example from the original poster):

 words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh'] print range(len(words)) 

This gives us a simple list:

 [0, 1, 2, 3, 4] 

... and the items in this list serve as β€œindices” in our results.

So do the same with our version of enumerate() :

 words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh'] print enumerate(words) 

This, of course, does not give us a list:

 <enumerate object at 0x7f6be7f32c30> 

... so put it on the list and see what happens:

 print list(enumerate(words)) 

This gives us:

 [(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')] 

These are actual key / value pairs.

So this is ...

 words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh'] for i in range(len(words)): print "words[{}] = ".format(i), words[i] 

... actually takes the first list (Words) and creates a second, simple range list, indicated by the length of the first list.

So, we have two simple lists, and we just print one item from each list to get our so-called key / value pairs.

But they are not really key / value pairs; these are just two separate items printed at the same time from different lists.

While the enumerate () code is:

 for i, word in enumerate(words): print "words[{}] = {}".format(i, word) 

... also creates a second list. But this list is actually a list of key / value pairs, and we request each key and value from one source, and not from two lists (for example, we did above).

So, we print the same results, but the sources are completely different - and they are processed in a completely different way.

+1
source share

The following code displays the number of words whose first and last letters are equal. Tested and verified using the python online compiler :

 words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh'] count = 0 for i in words: if i[0]==i[-1]: count = count + 1 print(count) 

Exit:

 $python main.py 3 
+1
source share
 c=0 words = ['challa','reddy','challa'] for idx, word in enumerate(words): if idx==0: firstword=word print(firstword) elif idx == len(words)-1: lastword=word print(lastword) if firstword==lastword: c=c+1 print(c) 
0
source share

Use range (), namely:

 for i in range(len(words)): ... 
-one
source share

All Articles