Search code examples
pythonindexingwhile-looprangeout

IndexError: list index out of range when if len(listx[i]) > n


I apologize in advance if my question is too basic. I have also tried to find answers in previous posts, but they are not exactly what I am looking for.

I am struggling with this exercise :

Write a program that analyzes all the elements of a word list one by one (for example example: ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']) for generate two new lists. One will contain words with less than 6 characters, the other is words of 6 characters or more.

liste1 = ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']

moins6 = []
plus6 = []
i = 0 

while i <= 13 :
    
    if len(liste1[i]) > 6: 
        moins6.append(liste1[i])
        
    else:
        plus6.append(liste1[i])
    
    i +=1 

I receive the error " IndexError: list index out of range "

Could you suggest me the right way to write it (with while loop)

Many thanks in advance


Solution

  • according to your code your value of i is going from 0 to 13

    while there are only 6 elements in your input list

    so your value of i should go from 0 to 5

    if you didn't know what your input size will be, you can use len() to find out

    liste1 = ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']
    
    moins6 = []
    plus6 = []
    i = 0 
    
    while i < len(liste1) : # here is your error
        
        if len(liste1[i]) > 6: 
            moins6.append(liste1[i])
            
        else:
            plus6.append(liste1[i])
        
        i +=1 
    print(liste1, moins6, plus6)
    
    ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra'] 
    ['Maximilien', 'Brigitte', 'Jean-Pierre'] 
    ['Jean', 'Sonia', 'Sandra']