Python Tips and Tricks For Beginners to Write Shorter Code
Python

Python Tips and Tricks For Beginners to Write Shorter Code

Editorial Team
Editorial Team

Follow us on Discord or Telegram to get access to free tutorials and updates.

Python is a language known for its simplicity and clean syntax. Python programs usually have lesser lines of code than other programming languages.

Now, lets learn some Python tips and tricks to make your code even more readable and shorter.

To download these Python tips and tricks as PDF, skip to the bottom of this post.

1. Python program to swap two numbers

This is one of the basic programs every newbie programmers will learn. The most common way of swapping two variables by using a third variable. In fact, there are a couple of other ways to swap two numbers.

1. Using a third variable

a = 5
b = 6
c = a
a = b
b = c

2. The Pythonic way

a, b = 5, 6
a, b = b, a

2. Reverse of a string

x = "Hello World"
print(x[::-1])

Output:

dlroW olleH

3. Python program to generate a list of numbers up to x

limit = int(input("Enter the limit: "))
l = [x for x in range(limit+1)]
print(l)

This is known as list comprehension.

Output:

Enter the limit: 5
[0, 1, 2, 3, 4, 5]

4. Python assignment expression

This is one of the major changes in Python 3.8 is the introduction of Assignment expressions. It is written using := and is known as “the walrus operator”.

The classic style:

key = ''
while(key != 'q'):
    key = input("Enter a number or q to exit ")
    if key != 'q':
        print(int(key)**2)

Using assignment operators:

while((key:= input("Enter a number or q to exit ")) != 'q'):
    print(int(key)**2)

5. Multiply a string

Hey, you can multiply strings in Python.

print("Geekinsta " * 3)

Output:

Geekinsta Geekinsta Geekinsta

6. Sort a list based on custom key

Following is a list of employees in company with their ID and salary.

emp=[
    ['EMPCT01', 10000],
    ['EMPCT02', 20000],
    ['EMPCT03', 80000],
    ['EMPCT04', 30000]
]

How will you sort the emp in ascending order based on the salary. Ie, starting with the one with the lowest salary to the highest-paid one.

emp=[
    ['EMPCT01', 10000],
    ['EMPCT02', 20000],
    ['EMPCT04', 30000],
    ['EMPCT03', 80000]
]

Solution:

emp=[
    ['EMPCT01', 10000],
    ['EMPCT02', 20000],
    ['EMPCT03', 80000],
    ['EMPCT04', 30000]
]
emp.sort(key=lambda els: int(els[1]))
print(emp)

7. Check if a string exists in another string

There are several methods to do this.

x = "Hi from Geekinsta"
substr = "Geekinsta"

# Method 1
if substr in x:
    print("Exists")

# Method 2
if x.find(substr) >=0:
    print("Exists")

# Method 3
if x.__contains__(substr):
    print("Exists")

8. Shuffle the items of a list

How do you usually shuffle the items in a list? Most of the Python beginners will be using a loop to iterate over the list and shuffle the items.

But python has an inbuilt method to shuffle list items. To use this method, we should first import random module.

from random import shuffle
l = [1, 2, 3]
shuffle(l)
print(l)

You will get different outputs each time you run the code.

9. Create string from a list

With the join method Python, we can easily convert the items of a list to string.

l = ['Join', 'this', 'string']
print(str.join(' ', l))

10. Pass list items as arguments

In Python, you can pass the elements of a list as individual parameters without specifying it manually by index using the * operator. This is also known as unpacking.

l = [5, 6]
def sum(x, y):
    print(x + y)

sum(*l)

11. Flatten a list of lists

Usually, we flatten a list of lists using a couple of nested for loops. Although this method works fine, it makes our code larger. So, here’s a shorter method to flatten a list using the itertools module.

import itertools
a = [[1, 2], [3, 4]]
b = list(itertools.chain.from_iterable(a))
print(b)

12. Interchanging keys and values of a Dictionary

Python allows you to easily swap the keys and values of a dictionary using the same syntax we use for dictionary comprehension. Here’s an example.

d = {1: 'One', 2: 'Two', 3: 'Three'}
di = { v:k for k, v in d.items()}
print(di)

13. Using two lists in a loop

We normally use the range() function or an inerrable object to create a for loop. We can also create a for loop with multiple interactable objects using the zip() function.

keys = ['Name', 'age']
values = ['John', '22']

for i, j in zip(keys, values):
    print(f'{i}: {j}')

14. Create a dictionary from two lists

We can combine the elements of two lists as key-value pairs to form a dictionary. Here’s an example.

keys = ['Name', 'age']
values = ['John', '22']

d = {k:v for k, v in zip(keys, values)}
print(d)

15. Pass dictionary items as a parameter

The key-value pairs of a dictionary can be directly passed as named parameters to any function in the same way we passed a list before.

d = {'age': 25, 'name': 'Jane'}

def showdata(name, age):
    print(f'{name} is {age} years old')

showdata(**d)

Download Python Tips and Tricks PDF

Click here to download this as PDF

We’ll be regularly updating this article more such tips and tricks to make your code shorter and readable.