List comprehensions are a powerful feature in Python that allows you to create lists in a concise and readable way. They consist of brackets containing an expression followed by a for clause, then zero or more for or if clauses. In this tutorial, we will explore how to use conditional expressions (also known as ternary operators) within list comprehensions.
Introduction to List Comprehensions
Before diving into conditional expressions, let’s review the basics of list comprehensions. A simple list comprehension can be used to create a new list from an existing iterable:
new_list = [x for x in range(1, 10)]
print(new_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
You can also add conditions to filter the elements:
new_list = [x for x in range(1, 10) if x % 2 == 0]
print(new_list) # Output: [2, 4, 6, 8]
Introduction to Conditional Expressions
Conditional expressions are a concise way to evaluate a condition and return one of two values. The syntax is as follows:
value = <exp1> if condition else <exp2>
For example:
age = 12
status = 'minor' if age < 21 else 'adult'
print(status) # Output: minor
Using Conditional Expressions in List Comprehensions
Now that we have covered the basics of list comprehensions and conditional expressions, let’s combine them. The syntax is as follows:
new_list = [<exp1> if condition else <exp2> for item in iterable]
For example:
numbers = [x for x in range(1, 10)]
status_list = ['even' if x % 2 == 0 else 'odd' for x in numbers]
print(status_list) # Output: ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Note that the for
clause should be at the end of the expression.
Multiple Conditions
You can also use multiple conditions in a list comprehension:
numbers = [x for x in range(1, 10)]
status_list = ['even' if x % 2 == 0 else 'number three' if x == 3 else 'odd' for x in numbers]
print(status_list) # Output: ['odd', 'even', 'number three', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Real-World Example
Suppose we have a list of strings and we want to create a new list with the length of each string, but if the string is empty, we want to use a default value:
strings = ['hello', '', 'world', None]
lengths = [len(s) if s is not None else 0 for s in strings]
print(lengths) # Output: [5, 0, 5, 0]
Conclusion
In this tutorial, we have covered the basics of list comprehensions and conditional expressions, and how to use them together to create powerful and concise code. We have also seen examples of using multiple conditions and real-world applications.