Python list comprehension if example

Python List Comprehension containing IF Condition

Python List Comprehension is used to create Lists. While generating elements of this list, you can provide condition that could be applied on the input lists to list comprehension.

In this tutorial, we will learn how to apply an if condition on input list(s) in List Comprehension.

Syntax

Following is the syntax of List Comprehension with IF Condition.

output = [ expression for element in list_1 if condition ]

where condition is applied, and the element (evaluation of expression) is included in the output list, only if the condition evaluates to True.

Examples

1. Filter only even numbers using List Comprehension

In this example, we shall create a new list from a list of integers, only for those elements in the input list that satisfy a given condition.

Python Program

list_1 = [7, 2, 6, 2, 5, 4, 3] list_2 = [ x * x for x in list_1 if (x % 2 == 0) ] print(list_2)

We have taken a list of integers. Then using list comprehension, we are generating a list containing squares of the elements in the input list, but with a condition that only if the element in input list is even number.

2. List Comprehension using If condition on multiple input lists

In this example, we shall create a new list from two lists of integers with a given condition.

Читайте также:  Adding css files to html

Python Program

list_1 = [1, 2, 3] list_2 = [4, 5, 6] list_3 = [ x * y for x in list_1 for y in list_2 if (x+y)%2 == 0 ] print(list_3)

Summary

In this tutorial of Python Examples, we learned how to use List Comprehension with an IF Condition in it.

Источник

Руководство по использованию list comprehension

У каждого языка программирования есть свои особенности и преимущества. Одна из культовых фишек Python — list comprehension (редко переводится на русский, но можно использовать определение «генератора списка»). Comprehension легко читать, и их используют как начинающие, так и опытные разработчики.

List comprehension — это упрощенный подход к созданию списка, который задействует цикл for, а также инструкции if-else для определения того, что в итоге окажется в финальном списке.

Преимущества list comprehension

У list comprehension есть три основных преимущества.

  1. Простота. List comprehension позволяют избавиться от циклов for, а также делают код более понятным. В JavaScript, например, есть нечто похожее в виде map() и filter() , но новичками они воспринимаются сложнее.
  2. Скорость. List comprehension быстрее for-циклов, которые он и заменяет. Это один из первых пунктов при рефакторинге Python-кода.
  3. Принципы функционального программирования. Это не так важно для начинающих, но функциональное программирование — это подход, при котором изменяемые данные не меняются. Поскольку list comprehensions создают новый список, не меняя существующий, их можно отнести к функциональному программированию.

Создание первого list comprehension

List comprehension записывается в квадратных скобках и задействует цикл for. В процессе создается новый список, куда добавляются все элементы оригинального. По мере добавления элементов их можно изменять.

Для начала возьмем простейший пример: создадим список из цифр от 1 до 5, используя функцию range() .

Источник

Python ‘if…else’ in a List Comprehension (Examples)

You can place an if. else statement into a list comprehension in Python.

["EVEN" if n % 2 == 0 else "ODD" for n in numbers]

Notice that the if. else statement in the above expression is not traditional if. else statement, though. Instead, it’s a ternary conditional operator, also known as the one-line if-else statement in Python.

Example

Given a list of numbers, let’s construct a list of strings that are odd/even based on what the corresponding number in the list of numbers is.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Use a list comprehension to create a new list that includes # "EVEN" for even numbers and "ODD" for odd numbers even_or_odd = ["EVEN" if n % 2 == 0 else "ODD" for n in numbers] print(even_or_odd) # Output: ["ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN"]

In this example, the if..else clause in the list comprehension checks to see if the number n is even (that is, if n is divisible by 2 with no remainder). If it is, the string “EVEN” is included in the new list; otherwise, the string “ODD” is included.

The Traditional Approach

Let’s see the traditional for loop with an if. else statement approach for comparison:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Create an empty list to store the results even_or_odd = [] # Use a for loop to iterate over the numbers for n in numbers: # Use an if..else statement to determine if the number is even or odd if n % 2 == 0: even_or_odd.append("EVEN") else: even_or_odd.append("ODD") print(even_or_odd) # Output: ["ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN", "ODD", "EVEN"]

Here’s a fun little illustration of converting the traditional approach to a list comprehension with an if…else statement:

One-Line If-Else Statements in Python

To add an if. else statement into a list comprehension in Python, you need to use a slightly modified version of an if. else statement, called the conditional operator.

The conditional operator in Python allows you to write conditional expressions in a shorter and more concise way. It is also known as the ternary operator because it takes three operands.

Here is the general syntax for using the conditional operator in Python:

Here, x and y are the values that will be returned based on the evaluation of the condition . If the condition evaluates to True , x will be returned; otherwise, y will be returned.

Here is an example of using the conditional operator to return the maximum of two numbers:

# Define two numbers x = 5 y = 10 # Use the conditional operator to return the maximum of x and y max = x if x > y else y # Print the maximum print(max) # Output: 10

The condition checks to see if x is greater than y . If it is, the value of x is returned; otherwise, it returns y .

The conditional operator can be useful whenever you want to write a conditional expression in a single line of code. It can make your code more readable and concise by avoiding multi-line if..else statements. Also, some argue it only makes the code shorter but less readable which is why some don’t use conditional operators at all.

To include an if. else statement into a list comprehension, you need to pass it as a conditional expression.

Example

Let’s take a look at another example of list comprehensions an if. else statements.

Here is an example of a for loop with an if. else statement that prints whether a number is odd or even in a list of numbers.

First, let’s start with the traditional approach:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for number in numbers: if number % 2 == 0: print(number, "is even") else: print(number, "is odd")
1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even

This for loop can be converted into a one-line list comprehension expression using a conditional operator if. else :

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print([f" is " for number in numbers])

The output of this expression would be the same as the original for loop:

1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even

Should You Place If…Else Statements in List Comprehensions?

Whether or not you should use list comprehension expressions with conditional operators in your code depends on your personal preferences and the specific requirements of your project.

Some developers never use one-liner shorthand like list comprehensions or conditional operators.

List comprehensions can be a concise and elegant way to write certain types of for loops, but they can also make your code more difficult to read and understand if you are not familiar with the syntax.

If you are working on a small project with no collaborators, using list comprehension expressions (with if. else statements) can make your code more concise and easier to write.

However, if you are working on a larger project and you are collaborating with other people on a project, it may be more beneficial to use longer and more descriptive for loops that are easier for other people to read and understand.

Ultimately, the decision to use list comprehension in your code should be based on the specific needs of your project, the level of experience and familiarity of the people working on the project, and the trade-off between conciseness and readability.

My personal take: A list comprehension with an if. else statement looks messy and I’d probably not use such expression ever in my code.

Thanks for reading. Happy coding!

Источник

Оцените статью