Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference next item in list: python

I'm making a variation of Codecademy's pyglatin.py to make a translator that accepts and translates multiple words. However, I'm having trouble translating more than one word. I've been able to transfer the raw input into a list and translate the first, but I do not know how to reference the next item in the list. Any help would be greatly appreciated.

def piglatin1():

    pig = 'ay'

    original = raw_input('Enter a phrase:').split(' ')
    L = list(original)
    print L
    i = iter(L)
    item = i.next()


    for item in L:

        if len(item) > 0 and item.isalpha():
            word = item.lower()
            first = word
            if first == "a" or first == "e" or first == "i" or first == "o" or first =="u":
                new_word = word + pig
                print new_word
            else:
                new_word = word[1:] + word[0:1] + pig
            # first word translated    
                L = []
                M = L[:]


                L.append(new_word)

                print L # secondary list created.

                again = raw_input('Translate again? Y/N')
                print again

                if len(again) > 0 and again.isalpha():
                    second_word = again.lower()
                    if second_word == "y":
                        return piglatin()
                    else:
                        print "Okay Dokey!"

        else:
            print 'Letters only please!'
            return piglatin1()
like image 600
Thomas Avatar asked Oct 18 '13 23:10

Thomas


People also ask

How do I find the next element in a list?

Get Next Element in Python List using next() First of all, convert the list into the iterative cycle using cycle() method. For that, you have to import the cycle from itertools which come preinstalled with Python. Then use the next() method to find the next element in the Python iterator.

Can I use next on a list in Python?

Python next() method returns the next element from the list; if not present, prints the default value. If the default value is not present, raise the StopIteration error. You can add a default return value to return if the iterable has reached its end.

How do you get the next value in Python?

Python next() Function The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.


1 Answers

I was working on this problem recently as well and came up with the following solution (rather than use range, use enumerate to get the index).

for index, item in enumerate(L):
    next = index + 1
    if next < len(L):
        print index, item, next

This example shows how to access the current index, the current item, and then the next item in the list (if it exists in the bounds of the list).

like image 77
acknapp Avatar answered Oct 16 '22 06:10

acknapp