Roughmar
Roughmar

Reputation: 425

Python - functions being called inside list bracket. How does it work?

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.

Upvotes: 4

Views: 2904

Answers (2)

Garrett Hyde
Garrett Hyde

Reputation: 5597

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]

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 992857

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

Upvotes: 7

Related Questions