Лист компрехеншн python if

if/else in a list comprehension

I have a list xs containing a mixture of strings and None values. How can I use a list comprehension to call a function on each string, but convert the None values to » (rather than passing them to the function)? I tried:

[f(x) for x in xs if x is not None else ''] 

but it gives a SyntaxError . What is the correct syntax? See List comprehension with condition if you are trying to make a list comprehension that omits values based on a condition. If you need to consider more than two conditional outcomes, beware that Python’s conditional expressions do not support elif . Instead, it is necessary to nest if / else conditionals. See `elif` in list comprehension conditionals for details.

The way the question is written, I’d argue that the correct answer would be [f(x if x is not None else ») for x in xs] .

12 Answers 12

You can totally do that. It’s just an ordering issue:

[f(x) if x is not None else '' for x in xs] 
[f(x) if condition else g(x) for x in sequence] 

And, for list comprehensions with if conditions only,

[f(x) for x in sequence if condition] 

Note that this actually uses a different language construct, a conditional expression, which itself is not part of the comprehension syntax, while the if after the for…in is part of list comprehensions and used to filter elements from the source iterable.

Читайте также:  Date java часовой пояс

Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the ternary operator ?: that exists in other languages. For example:

value = 123 print(value, 'is', 'even' if value % 2 == 0 else 'odd') 

That’s why I prefer to put the ternary operator in brackets, it makes it clearer that it’s just a normal expression, not a comprehension.

So the trick is «In list compression I write if before for then I have to add else part too». because if my l = [ 2, 3, 4, 5] then [x if x % 2 == 0 for x in l] give me error whereas [x if x % 2 == 0 else 200 for x in l] works. Yes I know to filter it I should write [ x for x in l if x % 2 == 0] . Sorry for botheration. Thanks for your answer.

An example: [x for x in range(50) if (x%3)==0] will return a list of integers divisible by 3. [x if (x%3)==0 for x in range(50)] is invalid, as x if (x%3)==0 is not a valid expression. @Grijesh, here is a counter-example to your rule (if before/after for): [x for x in range(50) if ((x%3)==0 if x>20 else False)] . This comprehension’s filter criterion will only match integers that are both divisible by three and greater than 20.

@Drewdin List comprehensions don’t support breaking during its iteration. You will have to use a normal loop then.

Let’s use this question to review some concepts. I think it’s good to first see the fundamentals so you can extrapolate to different cases.

Other answers provide the specific answer to your question. I’ll first give some general context and then I’ll answer the question.

Fundamentals

if/else statements in list comprehensions involve two things:

1. List comprehensions

They provide a concise way to create lists.

Its structure consists of: «brackets containing an expression followed by a for clause, then zero or more for or if clauses«.

Case 1

Here we have no condition. Each item from the iterable is added to new_list .

new_list = [expression for item in iterable] new_list = [x for x in range(1, 10)] > [1, 2, 3, 4, 5, 6, 7, 8, 9] 

Case 2

Here we have one condition.

Condition: only even numbers will be added to new_list .

new_list = [expression for item in iterable if condition == True] new_list = [x for x in range(1, 10) if x % 2 == 0] > [2, 4, 6, 8] 

Condition: only even numbers that are multiple of 3 will be added to new_list .

new_list = [expression for item in iterable if condition == True] new_list = [x for x in range(1, 10) if x % 2 == 0 if x % 3 == 0] > [6] 

But howcome we have one condition if we use two if in new_list ?

The prior expression could be written as:

new_list = [x for x in range(1, 10) if x % 2 and x % 3 == 0] > [6] 

We only use one if statement.

new_list = [] for x in range(1, 10): if x % 2 == 0 and x % 3 == 0: new_list.append(x) > [6] 

Just for the sake of argument, you can also use or .

Condition: even numbers or numbers multiple of 3 will be added to new_list .

new_list = [x for x in range(1, 10) if x % 2 == 0 or x % 3 == 0] > [2, 3, 4, 6, 8, 9] 

Case 3

Here we need the help of conditional expressions (Ternary operators).

2.Conditional Expressions

What are conditional expressions? What the name says: a Python expression that has some condition.

First the condition is evaluated. If condition is True , then is evaluated and returned. If condition is False , then is evaluated and returned.

A conditional expression with more than one condition:

 if condition else if condition else . 
age = 12 s = 'minor' if age < 21 else 'adult' >minor 

The value of s is conditioned to age value.

3.List Comprehensions with Conditionals

We put list comprehensions and conditionals together like this.

new_list = [ for in ] new_list = [ if condition else if condition else for in ] 

Condition: even numbers will be added as ‘even’ , the number three will be added as ‘number three’ and the rest will be added as ‘odd’ .

new_list = ['even' if x % 2 == 0 else 'number three' if x == 3 else 'odd' for x in range(1, 10)] > ['odd', 'even', 'number three', 'even', 'odd', 'even', 'odd', 'even', 'odd'] 

The answer to the question

[f(x) for x in xs if x is not None else ''] 

Here we have a problem with the structure of the list: for x in xs should be at the end of the expression.

[f(x) if x is not None else '' for x in xs] 

The specific problem has already been solved in previous answers, so I will address the general idea of using conditionals inside list comprehensions.

Here is an example that shows how conditionals can be written inside a list comprehension:

X = [1.5, 2.3, 4.4, 5.4, 'n', 1.5, 5.1, 'a'] # Original list # Extract non-strings from X to new list X_non_str = [el for el in X if not isinstance(el, str)] # When using only 'if', put 'for' in the beginning # Change all strings in X to 'b', preserve everything else as is X_str_changed = ['b' if isinstance(el, str) else el for el in X] # When using 'if' and 'else', put 'for' in the end 

Note that in the first list comprehension for X_non_str , the order is:

expression for item in iterable if condition

and in the last list comprehension for X_str_changed , the order is:

expression1 if condition else expression2 for item in iterable

I always find it hard to remember that expression1 has to be before if and expression2 has to be after else. My head wants both to be either before or after.

I guess it is designed like that because it resembles normal language, e.g. «I want to stay inside if it rains, else I want to go outside»

In plain English the two types of list comprehensions mentioned above could be stated as:

extract_apple for apple in apple_box if apple_is_ripe

mark_apple if apple_is_ripe else leave_it_unmarked for apple in apple_box

Источник

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!

Источник

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