Ternary operator

The ternary operator is shorthand for if else

Syntax:

expression1 if condition1 else expression2

Traditional way

Python3




age = 18
eligible = False
if age >= 18:
    eligible = True
else:
    eligible = False


One Liner

Python3




age = 18
eligible = True if age >= 18 else False


If the condition in the if statement is true, the first expression is returned otherwise expression in the else part is returned.

10 Useful Python One Liners That Developers Must Know

Python is known for its easy-to-code and intuitive syntax. And one-liners are like the cherry on the cake which makes Python a more beautiful and beloved programming language. There are numerous features in Python Language and one of its most loved features is its one-liners. Writing Code in Python is already easy compared to other programming languages and using the one-liners makes it more easier and cool. Now let’s see what are these Python one-liners.

Similar Reads

What are Python one-liners?

One-liners help to reduce the number of lines of code by providing alternative syntax which is both easier to read and concise. One-liners are the syntactic sugars, which by adding simplicity and readability to the code makes it “sweeter” for the users to understand and code. These are short but powerful programs to do the task in a single line of code. One-liners are not present in all programming languages thus, making Python stand out....

Why use Python one-liners?

One-liners help improve the code quality by conveying the same meaning in lesser lines of code. They reduce the unnecessary syntactic code which makes it more readable for others. Also, it helps save a lot of time and effort by allowing the programmers to focus more on logic implementation rather than syntax....

1. Swap two variables

Traditional Way...

2. List Comprehension

...

3. Lambda function

...

4. map(), filter() and reduce()

List comprehension is a shorthand method to create a new list by changing the elements of the already available iterable (like list, set, tuple, etc)....

5. Walrus

...

6. Ternary operator

...

7. Iterable or value Unpacking

...

8. Space-separated integers to a list

...

9. Leveraging print() to fullest

...

10. Printing variable name along with value using fstring

...

Conclusion

...

FAQs on Python One-liners

Lambda functions are anonymous functions i.e. functions without names. This is because they are mostly one-liners or are only required to be used once....