2

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.

t0v4
  • 49
  • 1
  • 5
  • 2
    You have an infinite loop because you continuously add elements to the loop you're consuming from. `with_title_words = words` does not do a deep copy. It's like a reference. – amiabl Jun 16 '20 at 10:31
  • 1
    Also, see this answer. https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list/2612990 – Axe319 Jun 16 '20 at 11:07

1 Answers1

0
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.

James
  • 247
  • 2
  • 6