Reputation: 3
What is wrong with this code? I must be missing something trivial. Every time I try to run it it does nothing for a while and then outputs 'Killed'. I wanted it to take every element in list, add "x" to it and then append this new element to the list, so that output would look like this:
['a', 'b', 'c', 'd', 'ax', 'bx', 'cx', 'dx']
My code so far:
list = ['a', 'b', 'c', 'd']
for element in list:
element = element + "x"
list.append(element)
print(list)
Upvotes: 0
Views: 288
Reputation: 1291
A cleaner way to do this would be to use extend
So you could do something like this:
l = ['a','b','c','d'] # DO NOT USE list as a variable name, it is a keyword in python
l.extend([element + 'x' for element in l])
print(l)
Also, the reason your code doesn't work is because you are essentially creating an infinite loop, because your loop keeps on adding elements to the list you are iterating over.
Using extend in the way I have mentioned above, would create a temporary list with the new items, and then add every item from the temporary list into the actual list.
Upvotes: 0
Reputation: 1874
Don't use list
, it is a keyword (as an example see the copy function I used in line 2)
You are appending to a list while iterating it, so this will result in an endless loop
base_list = ['a', 'b', 'c', 'd']
new_list = list.copy(base_list)
for element in base_list:
newelement = element + 'x'
new_list.append(newelement)
print(new_list)
Upvotes: 0
Reputation: 1513
What's wrong with this code? The answer is you have created an infinite loop since you continously add an element to a list as you iterate over it.
Upvotes: 0
Reputation: 13
After appending to the list2, i just added it to original list1, and got the desired result.
list1 = ['a', 'b', 'c', 'd']
list2 = []
for x in list1:
list2.append(x+'x')
print(list1+list2)
Upvotes: 0
Reputation: 186
list = ['a', 'b', 'c', 'd']
list2 = []
for element in list:
list2.append(element + "x")
list.extend(list2)
print(list)
Since you were appending inside the loop you used to get the memory error. The above code might help you.
Upvotes: 0
Reputation: 1824
You're appending to your list as you iterate over it, so every time you take a "step forward", you add another "step" to take later, so you're ending up with ['a', 'b', 'c', 'd', 'ax', 'bx', 'cx', 'dx', 'axx', 'bxx' ...]
. For a whole host of reasons similar to this, a general rule is you should avoid modifying a list as you iterate over it.
Try this instead
list_1 = ['a', 'b', 'c', 'd']
list_2 = [elem + 'x' for elem in list_1]
result = list_1 + list_2
print(result)
Upvotes: 1