In Python, you can use conditionals within list comprehensions to filter the items that are included in the final list. This is useful when you need to include only certain items that meet a certain criteria.
Here's an example of a list comprehension with a conditional:
# A list of numbersnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# A list comprehension that includes only even numberseven_numbers = [num for num in numbers if num % 2 == 0]# Print the listprint(even_numbers) |
In this example, we define a list of numbers called numbers, and use a list comprehension to create a new list called even_numbers that includes only the even numbers from the original list. The conditional (if num % 2 == 0) filters out any numbers that have a remainder of 1 when divided by 2.
You can also use a conditional expression within a comprehension to modify the items that are included in the final list. Here's an example:
# A list of numbersnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# A list comprehension that includes only even numbers and converts them to stringseven_number_strings = [str(num) if num % 2 == 0 else 'odd' for num in numbers]# Print the listprint(even_number_strings) |
In this example, we use a conditional expression (str(num) if num % 2 == 0 else 'odd') within the list comprehension to convert even numbers to strings, and replace odd numbers with the string 'odd'. The resulting list contains a mix of strings and the string 'odd', depending on whether the original number was even or odd.