Making Life Easy with Python

Making Life Easy with Python

Gone are those days of tedious works; with Python, you can write multiple lines of code in just a single line.

Introduction

Python is a popular programming language that is easy to learn and nice to work with. In this guide, you will learn some simple yet helpful tips to take your Python skills to the next level by writing more readable and professional code.

Let’s get right into it!

1. One-Liner If-Else:

There is a shorthand syntax for the if-else statement that can be used when the condition being tested is simple and the code blocks to be executed are short. Here's an example:

a = 2
b = 330
print("A") if a > b else print("B")

Also, you can have multiple else statements on the same line.

Example

  1. One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
  1. Here's another example,

     result = value_if_true if condition else value_if_false
    

    This syntax is equivalent to the following if-else statement:

     if condition:
         result = value_if_true
     else:
         result = value_if_false
    

Note:

The shorthand syntax can be a convenient way to write simple if-else statements, especially when you want to assign a value to a variable based on a condition.
However, it's not suitable for more complex situations where you need to execute multiple statements or perform more complex logic. In those cases, it's best to use the full if-else syntax.

2.One-Liner for-loop

You can use what is called "list comprehension" to loop through a list neatly with one line of code. This one is VERY VERY useful and can make the code and operations very simple and less cluttery. For example, let’s square each number in a list of numbers:

numbers = [1, 2, 3, 4, 5]
print([num * num for num in numbers])

The code above is equivalent to the code below:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    squares = num * num
    print(squares)

The Output will be the same in both cases:

[1, 4, 9, 16, 25]

3.Dictionary Comprehension

Using comprehension is not restricted to lists only. You can use a similar syntax with dictionaries, sets, and generators too. For instance, let’s use dictionary comprehension to square the values of a dictionary:

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print({ key: num * num for (key, num) in dict1.items() })

The output will be:

{'a': 1, 'b': 4, 'c': 9, 'd': 16}

4.Lambda Functions

In Python, a lambda function is a small anonymous function without a name. It is defined using the lambda keyword and has the following syntax:

lambda arguments: expression

Lambda functions are often used in situations where a small function is required for a short period of time. They are commonly used as arguments to higher-order functions, such as map, filter, and reduce.

Here is an example of how to use a lambda function:

# Function to double the input
def double(x):
  return x * 2

# Lambda function to double the input
lambda x: x * 2

The above lambda function has the same functionality as the double function defined earlier. However, the lambda function is anonymous, as it does not have a name.

Lambda functions can have multiple arguments, just like regular functions. Here is an example of a lambda function with multiple arguments:

# Function to calculate the product of two numbers
def multiply(x, y):
    return x * y

# Lambda function to calculate the product of two numbers
lambda x, y: x * y

Lambda functions can also include multiple statements, but they are limited to a single expression. For example:

# Lambda function to calculate the product of two numbers,
# with additional print statement
lambda x, y: print(f'{x} * {y} = {x * y}')

In the above example, the lambda function includes a print statement, but it is still limited to a single expression.

Lambda functions are often used in conjunction with higher-order functions, such as map, filter, and reduce which I will be covering in detail in the upcoming blogs.

5. One-Liner Functions

Just like the previous case, Functions can also be expressed in single lines depending on the complexity of the function.

Example

The given code below...

def sum(n1, n2):
    return n1+n2

...can be expressed in a single line, just like the code below.

def sum(n1, n2): return n1+n2

Smaller stuffs but not the least

Well, the above-mentioned shorthands are the major kinds of stuff but Python has more cards under its sleeves. So let's dive in, shall we?

1.Swap Two Variables without a third Variable

Swapping is so easy in Python, with no more third variable, and no other fancy ways. It's very simple here,


a = 1
b = 2

a, b = b, a
print("a=",a," b=",b)
# Now a = 2 and b = 1

2.Chain Comparisons

This one is pretty neat. Instead of doing this:

x > 0 and x < 200

You can write it down just like your regular mathematical way:

0 < x < 200

Both of them have the same meaning and results in Python.

3.Repeat Strings without Using Loops

You can multiply a string by an integer to repeat it as many times as you prefer.

It's simple but super super handy.

Example

word="Swappy"
print(word*4)

Output

SwappySwappySwappySwappy

4.Reverse a String

Well, Action speaks better than words,

Example

sentence = "This is just a test"
print(sentence[::-1])

Output

tset a tsuj si sihT

5.Tear Values to Variables from a List

You can easily destructure list elements into separate variables and here is how you can do that:

Example

arr = [1, 2, 3]
a, b, c = arr
print(a, b, c)

Output

1 2 3

6.Simulate Choices

You can use the choice() method of the random module to pick random elements from a list.

Example

import random
print(random.choice(['Head',"Tail"]))

Output

Head

# I ran the code 32 times and everytime it gave me a Head, donno why

7.Join a List of Strings to One String

You can neatly join a list of strings together using the join() method of a string.

Example

words = ["This", "is", "a", "Test"]
print(" ".join(words))

Output

This is a Test

Conclusion

Well, that's a wrap for now!! Hope you folks have enriched yourself today with lots of known or unknown concepts. I wish you a great day ahead and till then keep learning and keep exploring!!

Did you find this article valuable?

Support Swapnoneel Saha by becoming a sponsor. Any amount is appreciated!