Search code examples
python-3.xfor-loopinfinite-loop

Python 3.8: for loop goes infinite


I have a list with strings as elements. All of them are in lower case. I want to modify the list so that this list also contains the strings in upper case for the first letter. I wrote this for loop:

> words = ["when", "do", "some", "any"]     
with_title_words = words
> 
>     for u in words:
>         u.title()
>         with_title_words.append(u)
>     print(with_title_words)

When I execute it goes infinite. It outputs all the string elements starting with the capital letter.


Solution

  • words = ["when", "do", "some", "any"]
    with_title_words = words[:]
    
    for word in words:
        with_title_words.append(word.title())
    
    print(with_title_words)
    

    Outputs:

    ['when', 'do', 'some', 'any', 'When', 'Do', 'Some', 'Any']
    

    or create an empty list word_title_words = [] to add only the titled strings.