views:

82

answers:

2

I was looking for an algorithm to replace some content inside a list with another. For instance, changing all the '0' with 'X'.

I found this piece of code, which works:

 list = ['X' if coord == '0' else coord for coord in printready]

What I would like to know is exactly why this works (I understand the logic in the code, just not why the compiler accepts this.)

I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').

This is probably thoroughly documented, but I have no idea on what this thing is called.

+6  A: 

This construction is called a list comprehension. These look similar to generator expressions but are slightly different. List comprehensions create a new list up front, while generator expressions create each new element as needed. List comprehensions must be finite; generators may be "infinite".

Greg Hewgill
Thanks for the speedy answer. Will try and understand it a little better now. =)
Roughmar
+3  A: 

I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').

If you're going to substitute multiple variables, I would use a dictionary instead of an "elif". This makes your code easier to read, and it's easy to add/remove substitutions.

d = {'0':'X', '1':'Y', '2':'Z'}
lst = [d[coord] if coord in d else coord for coord in printready]
Garrett Hyde
Better yet, `[d.get(coord, coord) for coord in printready]`, using the `default` param
Daenyth
Thank you for the dictionary tip. It was really helpful!
Roughmar