Python Tips and Tricks That Beginners Should Know

Introduction

Python is the high-level, general-purpose programming language developed by Guido Van Rossum in 1991. It is one of the most popular programming languages for the last three years according to Google.

Python language is relatively easy to learn and understand. Python has many applications(python applications) from web development to GUI development and is used in the leading technologies such as machine learning, robotics, artificial intelligence, and data science.

Python provides lots of libraries to ease while programming. In this blog post, we are going to discuss how we can use those built-in functions so that we can make better projects in python.

 

Python Tips & Tricks

Some of the python tips and tricks are given below:

1. Reversing a string

# Reversing a string

string = 'CodeFires'
print(string[::-1])

Output

seriFedoC

 

2. Creating a single string from all the elements in a list

str_list = ['I', 'love', 'Programming']

print(" ".join(str_list))

Output

I love Programming

 

3. Return multiple values from functions

# Return multiple values from function

def multipleValue():
    return 1, 2 , 3 , 4

x, y, z, a = multipleValue()
print(x, y, z, a)

Output

1 2 3 4

 

4. Check the memory usage of an object

# Memory usage of an object

import sys

x = 777
print(sys.getsizeof(x))

Output

28

 

5. Print any string N times

# print string N times

N = 3
string = 'Code'
print(string * N)

Output

CodeCodeCode

 

6. Create a dictionary from two related sequences

# dictionary from two related lists

list1 = ('x', 'y', 'z')
list2 = (100, 200, 300)

print(dict(zip(list1, list2)))

Output

{'x': 100, 'y': 200, 'z': 300}

 

7. Swapping of two numbers

x, y = 50, 100
x, y = y, x

print(x, y)

Output

100 50

 

8. Chaining of comparison operators

n = 77

# chaining of same operator(<)
result = 7 < n < 777
print(result)

# chaining of mixed operators
result = 70 > n <=84
print(result)

Output

True
False

 

9. Remove duplicates in a list

list1 = ['a', 'a', 'b', 'c', 'c', 'd', 'e', 'e', 'e', 'f', 'g']

list2 = [1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 7]

print(set(list1))
print(set(list2))

Output

{'g', 'c', 'a', 'e', 'd', 'b', 'f'}
{1, 2, 3, 4, 5, 6, 7}

 

10. Check your python working directory

import os

dirpath = os.getcwd()

print(dirpath)

Output

D:\PythonProjects\tips and tricks>

Note: To change the working directory use chdir() method of the os library as os.chdir(r’your directory path’)

 

11. Generate random numbers

import random

# for generating random numbers between
# lower and upper limit
random1 = random.randint(7, 777)
print(random1)

# for generating step wise 
# use randrange(start, stop, step)
random2 = random.randrange(7, 777, 10)
print(random2)

Output

476
317

 

12. Opening a web page

import webbrowser

url = r'http://codefires.com'

webbrowser.open(url)

 

13. Find Greatest Common Divisor(GCD)

import math

gcd1 = math.gcd(80, 160)
gcd2 = math.gcd(75, 125)

print(gcd1)
print(gcd2)

Output

80
25

 

14. Merge two dictionaries

dict1 = {"Ram": 100, "Shyam": 500 }
dict2 = { "Sita": 200, "Gita": 300}

dict3 = {**dict1, **dict2}

print(dict3)

Output

{'Ram': 100, 'Shyam': 500, 'Sita': 200, 'Gita': 300}

 

15. Extract numbers from string

# import python regex
import re

# initialise string
string = "Total 4 members climbed the height of 8848 meters in 2021"

# print original string
print("The original string : " + string)

# use re.findall()
temp = re.findall(r'\d+', string)

# as default type is string
# map string to int and make list
extracted_no = list(map(int, temp))

print(extracted_no)

Output

The original string : Total 4 members climbed the height of 8848 meters in 2021
[4, 8848, 2021]

 

16. Arithmetic operators in strings and lists

str1 = "Welcome to"
str2 = "CodeFires!!!"

# concatenate strings
print(str1 +" "+ str2)

list1 = [4, 5, 6, 7]
list2 = [8, 9, 10, 11]

# concatenate lists
print(list1 + list2)

Output

Welcome to CodeFires!!!
[4, 5, 6, 7, 8, 9, 10, 11]

 

17. Break the sentences into words

string = 'Python Tips and Tricks For Beginners'

break_into_lst = string.split(' ')

print(break_into_lst)

Output

['Python', 'Tips', 'and', 'Tricks', 'For', 'Beginners']

 

18. Advanced print options

# with sep parameter

str1 = 'pythonists'
str2 = 'python.org'

print(str1, str2, sep='@')

# with end paramerter
print('Ram', end=', ')
print('Shyam', end=', ')
print('Sita', end='.')

Output

pythonists@python.org
Ram, Shyam, Sita.

 

19. Enumerate function

Enumerate() is the python method that adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples uing list() method.

Syntax

enumerate(iterable, start=0)

Parameters:

iterable: any object that supports iteration

start: the index value from which the counter
       is to be started, by default it is 0

Program

football_clubs = ['Barcelona', 'Real Madrid', 'Liverpool',
                'Manchester United', 'Juventus']

# Classical approach
i = 0
for club in football_clubs:
    i += 1
    print(i, club)

# Using enumerate()
for i, club in enumerate(football_clubs, 1):
    print(i, club)

Output

1 Barcelona
2 Real Madrid
3 Liverpool
4 Manchester United
5 Juventus
'''

 

20. List comprehension

List comprehensions are an elegant way to build a list without having to use different for loops to append values one by one.

Simplest form

[expresssion-involving-loop-variable for loop-variable in sequence]

Program

# Creating list of integers from 0 to 9
ListOfNumbers = [x for x in range(10)]

print(ListOfNumbers)

Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

Conclusion

Here in this blog, we discussed python tips and tricks that can be used while doing python programming. Which tips do you like the most? Don’t forget to comment down in the comment section.

Happy coding 🙂

Leave a Comment