What is the output of the following?x = ['ab', 'cd']for i in x: x.append(i.upper())print(x)
Question
What is the output of the following?
x = ['ab', 'cd']
for i in x:
x.append(i.upper())
print(x)
Solution
The code you've posted will result in an infinite loop.
Here's why:
- You're iterating over the list
x
which initially contains two elements: 'ab' and 'cd'. - Inside the loop, you're appending to the same list (
x
) you're iterating over. You're adding the uppercase version of each item to the end of the list. - Because you're adding to the list during iteration, the loop will never reach the end of the list, resulting in an infinite loop.
In general, it's not a good idea to modify a list (or any iterable) while iterating over it. If you need to create a new list that contains the original elements and the uppercase versions, you could create a copy of the original list to iterate over.
Similar Questions
What will be the output of the following Python code?x=[[]]*4x[1].append(7)print(x)
What will the output be of the following code?D = {1:['Raj', 22], 2:['Simran', 21], 3:['Rahul', 40]}for val in D: print(val)
What will the output of the following code be?l = [32, 34, 12, 27, 33]l.append([14, 19])print(len(l))
What will be the output of the following Python code snippet?print([[i+j for i in "abc"] for j in "def"])
l = [1,2,3,4,5,6]l.append([a,b,c,d,e,f,g,h,i,j,k])print(len(l))What will be the output of this code in python
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.