Python’s conditional expressions were designed exactly for this sort of use-case:
>>> l = [1, 2, 3, 4, 5]
>>> ['yes' if v == 1 else 'no' if v == 2 else 'idle' for v in l]
['yes', 'no', 'idle', 'idle', 'idle']
More Related Contents:
- How can I use a conditional expression (expression with if and else) in a list comprehension? [duplicate]
- Python: Does Python have a ternary conditional operator?
- What does “list comprehension” and similar mean? How does it work and how can I use it?
- Flattening a shallow list in Python [duplicate]
- Is it Pythonic to use list comprehensions for just side effects?
- List comprehension without [ ] in Python
- Generator expressions vs. list comprehensions
- Are list-comprehensions and functional functions faster than “for loops”?
- List comprehension on a nested list?
- Create list of single item repeated N times
- if else in a list comprehension [duplicate]
- Why is there no tuple comprehension in Python?
- How do I create a list of lambdas (in a list comprehension/for loop)?
- Why is a list comprehension so much faster than appending to a list?
- List comprehension vs generator expression’s weird timeit results?
- Is it possible to use ‘else’ in a list comprehension? [duplicate]
- Comprehension for flattening a sequence of sequences? [duplicate]
- Advanced Nested List Comprehension Syntax
- Weird behavior: Lambda inside list comprehension [duplicate]
- How to handle exceptions in a list comprehensions?
- Is it possible to access current object while doing list/dict comprehension in Python?
- Python using enumerate inside list comprehension
- Nested dictionary comprehension python
- How to remove multiple items from a list in just one statement?
- How to read aloud Python List Comprehensions?
- Flattening a list of NumPy arrays?
- How do I convert a tuple of tuples to a one-dimensional list using list comprehension? [duplicate]
- flatten list of list through list comprehension
- Converting List Comprehensions to For Loops in Python
- Optimal method to find the max of sublist items within list