Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 434
Roughmar Avatar asked Dec 22 '22 22:12

Roughmar


2 Answers

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]
like image 26
Garrett Hyde Avatar answered Dec 24 '22 11:12

Garrett Hyde


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

like image 106
Greg Hewgill Avatar answered Dec 24 '22 12:12

Greg Hewgill