简体   繁体   中英

What's wrong with this python code? (beginner's question)

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)

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

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)  

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM