I am trying to run this code but I got nothing.Can anyone tell me why It gives nothing.
thislist = ["apple", "banana", "cherry"]
for x in thislist:
thislist.append(x.upper())
print(thislist)
CodePudding user response:
you are iterating over a list that you are adding to meaning you will never reach the end of the list since every loop you an an extra item. Instead iterate over a slice of the list
thislist = ["apple", "banana", "cherry"]
print(thislist)
for x in thislist[:]:
thislist.append(x.upper())
print(thislist)
OUTPUT
['apple', 'banana', 'cherry']
['apple', 'banana', 'cherry', 'APPLE', 'BANANA', 'CHERRY']
CodePudding user response:
Use this Code
thislist = ["apple", "banana", "cherry"]
newlist = []
for x in range(len(thislist)):
newlist.append(thislist[x].upper())
print(newlist)
Happy Learning :)
CodePudding user response:
Because you created an infinite loop. try this:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
thislist[i] = thislist[i].upper()
print(thislist)
And you will get:
['APPLE', 'BANANA', 'CHERRY']