No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python Ternary List Comprehension

by Khaleel O.
January 13, 2024
in Python
Reading Time: 4 mins read
A A
python ternary list comprehension
python ternary in list comprehension

Let’s investigate Python ternary list comprehension with some code examples. 🔥🔥

The ternary operator in Python is a concise way to execute an “if-else” condition within a single line or expression. It allows for conditional assignment of values. The basic syntax of the ternary operator is:

value_if_true if condition else value_if_false

Here’s how it works:

  • condition: This is the boolean expression that the ternary operator evaluates.
  • value_if_true: The value to be assigned if the condition is True.
  • value_if_false: The value to be assigned if the condition is False.

This operator is particularly useful for short and readable conditional assignments. Here’s a simple example:

x = 5
result = "Greater than 10" if x > 10 else "Less than or equal to 10"
print(result)

#Output
#Less than or equal to 10

In this example, result will be “Less than or equal to 10” because the condition x > 10 is False. If x were greater than 10, result would be “Greater than 10”.

The Python ternary operator in list comprehensions is an efficient way to evaluate conditions within the same. Here are two simple examples:

print(["even" if x % 2 == 0 else "odd" for x in range(1, 6)])

#output
#['odd', 'even', 'odd', 'even', 'odd']

For the first one, all we’re doing is creating a list of “even” or “odd” based on the parity of numbers in a range. This list comprehension iterates through numbers from 1 to 5. For each number x, it checks if x is divisible by 2 (x % 2 == 0). If it is divisible, “even” is added to the list; otherwise, “odd” is added. The result is a list that labels each number as either “even” or “odd”.

Here’s another example:

print(["positive" if x > 0 else "negative" for x in [-2, -1, 0, 1, 2]])

#output
#['negative', 'negative', 'negative', 'positive', 'positive']

Here, we’re creating a list of “positive” or “negative” based on the sign of numbers in an existing list. This list comprehension iterates through a predefined list of numbers: [-2, -1, 0, 1, 2]. For each number x in this list, it checks if x is greater than 0. If x is greater than 0, “positive” is added to the new list; if x is less than or equal to 0, “negative” is added. The result is a list indicating whether each number is “positive” or “negative”.

Finally, let’s do more complex examples of a Python Ternary In a List Comprehension:

print(["small" if x < 5 else ("medium" if x < 10 else "large") for x in range(1, 15)])

#output
#['small', 'small', 'small', 'small', 'medium', 'medium', 
#'medium', 'medium', 'medium', 'large', 'large', 'large', 'large', 'large']

Here, we are using a nested ternary operator for categorizing numbers. For each number x in the range from 1 to 14, it categorizes x as “small” if it’s less than 5, “medium” if it’s between 5 and 9, and “large” if it’s 10 or greater. The result is a list that classifies each number into one of these three categories.

Here’s another complex example:

print([sublist[:2] if len(sublist) > 3 else sublist for sublist in [[1, 2, 3], [4, 5, 6, 7], [8, 9]]])

#Output
#[[1, 2, 3], [4, 5], [8, 9]]

This list comprehension operates on a list of lists. For each sublist in the outer list, it checks if the length of the sublist is greater than 3. If it is, only the first two elements of the sublist are included in the new list (sublist[:2]). If the sublist has 3 elements or fewer, the entire sublist is included. The resulting list is a mix of full and truncated sublists, depending on their initial sizes.

So there you have it! You learned how to use Python Ternary In List Comprehension. Happy coding! 🔥🔥🔥

Tags: list comprehensionpythonternary
Previous Post

e in Python Examples

Next Post

Python Deque Methods

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy