In this tutorial, we will look at how to create a list using a list comprehension that uses an if else logic to decide the final list values.
List comprehensions offer a concise way to create lists in Python and are particularly useful when creating lists using other iterables, filtering lists, etc.
Let's say you have a list, say ls
of integers 1 to 10 (both inclusive) and you want to create a new list, say new_ls
that contains the string "odd" or "even" depending on whether the corresponding value in ls
is odd or even.
Using a list comprehension can be a valid approach for such cases.
How to use if else
logic inside a list comprehension in Python?
Use the following syntax to incorporate an if else
logic inside a list comprehension.
new_ls = [expression if condition else other_expression for member in iterable]
Here, for each member
in the iterable
we are checking for our condition
which if it evaluates to True
, we use the value resulting from expression
otherwise we use the value resulting from other_expression
as our resulting value in the list comprehension.
Let's now look at an example.
Let's create a list with string values "odd" and "even" for corresponding value in the ls
list.
# list of integers from 1 to 10
ls = range(1, 11)
# create list using list comprehension
new_ls = ["odd" if num % 2 != 0 else "even" for num in ls]
print(new_ls)
Output:
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']
We get a list with "odd" and "even" values. For example, for the value 4
in the list ls
, its corresponding value in the list new_ls
is "even"
Filter values with if
in list comprehension
Note that you can also just use the if
statement (without the else
part) inside the list comprehension. This is commonly used when filtering lists.
Use the following syntax to use just the if
construct inside a list comprehension.
new_ls = [expression for member in iterable if condition]
Here, for each member
in the iterable
we are checking for our condition
which if it evaluates to True
, we use the value resulting from expression
as our resulting value in the list comprehension otherwise we don't do anything (skip that member).
For example, let's filter the above list of integers ls
to create a new list with only odd integers.
# list of integers from 1 to 10
ls = range(1, 11)
# create list of odd values in ls using list comprehension
odd_ls = [num for num in ls if num % 2 != 0]
print(odd_ls)
Output:
[1, 3, 5, 7, 9]
We get a list of only the odd numbers in ls
.
Top comments (0)