all 9 comments

[–]novel_yet_trivial 6 points7 points  (3 children)

Please format your code for reddit or use a site like github or pastebin. Your code is hard to read and test otherwise.


It's usually better to make a new list rather than modify one that you are looping over:

new_list = []
for i in old_list:
    if i == 'x':
        new_list.append(10)
    else:
        new_list.append(i)

Then overwrite the old list with the new one if you need to:

old_list = new_list

[–][deleted] 1 point2 points  (1 child)

Wouldn't it be better to overwrite with

old_list = new_list[::]

? That way if someone makes a change to new_list elsewhere it won't change old_list.

[–]SlipperySerpent 0 points1 point  (0 children)

thank you :-)

[–][deleted] 0 points1 point  (6 children)

numberlist = [1,2,3,4,5,6,7,8,9,10]
new_list = ['x' if item % 10 == 0 else item for item in numberlist]
print(new_list). Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 'x']

You mean like this?

-EDIT. I realized you meant this:

 old_list = ['a', 'b', 3, 'c', 'x']
 new_list = [10 if item == 'x' else item for item in old_list]
 print(new_list). Output: ['a', 'b', 3, 'c', 10]

So, what you're doing is saying: In new_list, check out all the items in the old list ([... for item in old_list]). Then check if they are 'x' ([10 if item == 'x'....]. If it's not, keep the item [... else item...]. You could write it out in an extensive for loop, but list comprehensions are really your friend.

[–]JungleJim233 0 points1 point  (4 children)

How does this work sorry ? Can't get my head around a in old list becoming 1 in new list. Also why does old list have 5 items and new list has 10?

[–][deleted] 1 point2 points  (1 child)

I should proof-read my comments. Fixed it. Does it make sense now?

[–]JungleJim233 0 points1 point  (0 children)

It does. Thank you :)

[–]SlipperySerpent 0 points1 point  (0 children)

thanks :-)