Python Forum

Full Version: Alernating the two items in a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody ,

I am trying to make a list by alternating two values but I am getting error. Basically my list should be like if it starts with 2 should go on 3 like [2 3 2 3 2] or if it starts with 3 should go on [3 2 3 2 3] . I coded as below but I am getting the "list assignment index out of range" error. I am very beginner in python and I would be very happy if you can help me ;

Thank you in advance

Regards

    tm=[2,3]
                L=[]
    for i in range(5):
        number=(random.choice(tm))
        L.append(number)
        if(L[i]==2):
            L[i+1]=3
        else:
            L[i+1]=2

I solved it :)
After you append, L[i] is the last item in the list. So L[i+1] doesn't exist yet, and that's why you are getting the error. The index (i+1) is out of range (outside the list). Just replace those two assignments with appends and you'll be fine.

Note that with that fix, your code will produce a list that is ten items long, and may have values like: [2, 3, 3, 2, 2, 3, 2, 3, 3, 2]. If you want a five item long list with strict alternation, you need to move getting the random number and adding it to the list outside of the loop.