One-Liners in Python
Python boasts a concise and straightforward syntax, making it ideal for beginners and experienced developers alike. With its emphasis on readability and simplicity, Python allows users to express concepts in fewer lines of code compared to other programming languages. Its minimalist approach minimizes unnecessary punctuation, enabling developers to focus on problem-solving rather than syntax complexities. Python’s elegant design promotes code clarity and maintainability, facilitating rapid development and reducing debugging time. Whether creating simple scripts or complex applications, Python’s intuitive syntax streamlines development, making it a popular choice for a wide range of projects. Here is a list of Python one-liners that will make you code like a pro.
1. Swap variables
1 2 3 4 5 |
a = 10; b = 20; a, b = b, a; print(a, b) # 20 10 |
2. Reverse a List
1 2 3 |
arr = [1, 2, 3, 4, 5, 6]; print(arr[::-1]); # [6, 5, 4, 3, 2, 1] |
3. Reverse a String
1 2 3 |
s = "Hello"; print(s[::-1]); # olleH |
4. Get the sum of a List
Python has a built in sum() function, that adds up all the values present in the list.
1 2 3 |
list = [1, 2, 3, 4, 5, 6, 7]; print(sum(list)); # 28 |
5. Check a String is Palindrome or not
A string is said to be a palindrome if the original string and its reverse are the same. You can check if a string is a palindrome or not using the following code:
1 2 3 4 5 |
string = "rider"; print('Yes') if string == string[::-1] else print('No') # No string2 = "malayalam"; print('Yes') if string2 == string2[::-1] else print('No') # Yes |
6. Factorial of a Number
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. You can find the factorial of a number in one line of code using lambda functions. To get factorial of a number you can use the below code :
1 2 3 4 5 |
num1 = 5; factorial = lambda num : 1 if num <= 1 else num*factorial(num-1); print("Factorial of", num1, ":", factorial(num1)); # Factorial of 5 : 120 |
7. Lambda Function
Lambda function replaces a function wherever a single expression is to be evaluated.
1 2 3 4 5 6 7 8 9 10 |
def sqr(x): return x * x print(sqr(5)) # 5 # Using Lambda Function sqrLambda = lambda x: x * x print(sqrLambda(5)) # 5 |
I hope these one-liners will help you make more effective use of Python in your future projects.