Python For loop, how to store last iteration as a variable

Hello FreeBSD, I gravel at your godly presents. I have a quick question, and was hoping someone could mention a phrase that will make something click, or maybe point me in the right direction.

here is the problem.

I want to create a Palindrome function that will iterate over an outside list, then return the number of Palindrome found.

here is what I have been tunnel visioning into.

Code:
def main():
    x=0   
    word=['mom','dad','pap','nan','cat','booger','shit','uber','redrum','pop','poop','sarah','nate','hannah']
    for i in word:
        if(i[::-1]==i):
            x +=1
            print(x)

main()

this returns
Code:
Python 3.3.0 (v3.3.0:, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
1
2
3
4
5
6
7
>>>

I was hoping to just have main(): return 7, but when I return(x) it returns 1. Samething with print, if I print(i) it returns 'mom'.


Now this is probably redundant but, I also tryed to create two empty list Non_pal=[] and pal=[], and if(i[::-1]==i): paladrome.append(i). same for Non-pal

Now that worked perfectly, it gave me two lists with Non-palindrome[] and palindrome[] words, but when I return the value I get.

Code:
>>> main() 
['mom']
['mom', 'dad']
['mom', 'dad', 'pap']
['mom', 'dad', 'pap', 'nan']
['mom', 'dad', 'pap', 'nan', 'pop']
['mom', 'dad', 'pap', 'nan', 'pop', 'poop']
>>> main() # returning non-pal this time
['cat']
['cat', 'booger']
['cat', 'booger', 'shit']
['cat', 'booger', 'shit', 'uber']
['cat', 'booger', 'shit', 'uber', 'redrum']  # sorry for lack of vocab words
>>>


could anyone shed some light. My main goal is to
print 'Number of words:', words
print 'Number of Palindromes:', palindromes
 
Incase anybody starting out, and might be mildly retarded, I figured I would post the solution to my problem.



ok
Code:
def main():
    word=['mom','dad','pap','nan','cat','booger','shit','uber','redrum','pop','poop','hannah','nate','sarah']
    paladrome=[]
    non_paladrome=[]
    for i in word:
        if (i[::-1]==i):
            paladrome.append(i)
        if (i[::-1]!=i):
            non_paladrome.append(i)
    print('length of list is: ', len(word))
    print('number of Paladrome is: ', len(paladrome))
I needed to get outside of the if statement, and back to the For?
anyway it returns
Code:
>>> ================================ RESTART ================================
>>> 
>>> main()
length of list is:  14
number of Paladrome is:  7
>>>
 
I needed to get outside of the if statement, and back to the For?

I don't quite understand this question, but your test can be better written as:

Code:
        if (i[::-1] == i):
            paladrome.append(i)
        else:
            non_paladrome.append(i)
 
Back
Top