top 30 python tips and tricks for beginners

Welcome to my Blog, In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

Here we take two number x and y. swap the numbers means x value assign in y and y value assign in x.

x, y = 10, 20
print(x, y)  #10 20 
x, y = y, x
print(x, y)  #20 10

2) Reversing a string in Python.

a = "hereisastring"
print("Reverse is", a[::-1])  #gnirtsasiereh

3) Create a single string from all the elements in list.

a = ["let", "code", "together"] 
print(" ".join(a))

4) Chaining Of Comparison Operators.

n = 10
result = 1 < n < 20
print(result)  #True
result = 1 > n <= 9
print(result)  #False

5) Print The File Path Of Imported Modules.

import os 
import socket 
print(os)          #<module 'os' from '/usr/lib/python3.5/'>
print(socket)      #<module 'socket' from '/usr/lib/python3.5/'>

6) Return Multiple Values From Functions.

def x(): 
    return 1, 2, 3, 4
a, b, c, d = x() 
print(a, b, c, d)   #1 2 3 4

7) Find The Most Frequent Value In A List.

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] 
print(max(set(test), key = test.count))    #4

8) Check The Memory Usage Of An Object.

import sys 
x = 1
print(sys.getsizeof(x))    #28

9) Print string N times.

n = 2
a = "ourcodesolution"
print(a * n)    #ourcodesolutionourcodesolutionourcodesolution

10) Checking if two words are anagrams.

from collections import Counter 
def is_anagram(str1, str2): 
     return Counter(str1) == Counter(str2) 
# or without having to import anything  
def is_anagram(str1, str2):  
    return sorted(str1) == sorted(str2)

print(is_anagram('cdab', 'abcd'))    #True
print(is_anagram('jkin', 'nikj'))    #False

11) Convert it to a single list without using any loops.

import itertools 
a = "ourcodesolution"
print(list(itertools.chain.from_iterable(a)))     #['o', 'u', 'r', 'c', 'o', 'd', 'e', 's', 'o', 'l', 'u', 't', 'i', 'o', 'n']

12) Convert list of list into single list.

# import the itertools  
import itertools  
# Declaring the list geek  
ourllist = [[1, 2], [3, 4], [5, 6]]  
# chain.from_iterable() function returns the 
# elements of nested list  
# and iterate from first list  
# of iterable till the last  
# end of the list  
lst = list(itertools.chain.from_iterable(ourllist))  
[1, 2, 3, 4, 5, 6]

13) Printing the repeated characters: Task is to print the pattern like this Geeeeekkkkss. So we can easily print this pattern without using for loop.

# + used for string concatenation 
# To repeat the character n times, just multiply n  
# with that character   
print ("A" + "b"*5 + "C"*4 + "D"*2)   #AbbbbbCCCCDD

14) sorted.

sorted_Data = sorted(data,reverse=True)
print(sorted_Data)    #[10, 9, 5, 3, 1]

15) Dict sorted.

sorted_data=sorted(data,key=lambda x:x["age"])
print(sorted_data)    #[{'name': 'Max', 'age': 6}, {'name': 'Ben', 'age': 9}, {'name': 'Lisa', 'age': 20}]

16 ) store unique values insets.

my_set = set(my_list)
print(my_set)   #{1, 2, 3, 4, 5, 6, 7}

17) save memory with generators.

import sys
my_list=[i for i in range(10000)]
print(sum(my_list))                           #49995000
print(sys.getsizeof(my_list),"bytes")         #87624 bytes

my_gen=(i for i in range(10000))
print(sum(my_gen))                            #49995000
print(sys.getsizeof(my_gen),"bytes"           #88 bytes

18) define default values in dict with .get() or .defaults.

count = my_dict.get('count',0)
print(count)  #0

count = my_dict.setdefault('count',0)
print(count) #0

19) count hashable objects with collections.counter

from collections import Counter
counter = Counter(my_list)
print(counter)      #Counter({9: 5, 10: 3, 5: 2, 2: 1})
print(counter[10])  #3
print(counter[3])   #0

most_common = counter.most_common(2)
print(most_common)     #[(9, 5), (10, 3)]

20) merge two dict.

d1 = {"name":"alex","age":25}
d2 = {"name":"alex","city":"mumbai"}
print(merged_dict)   #{'city': 'mumbai', 'age': 25, 'name': 'alex'}

21) use all and any in python.

comment = 50
condition = [
if all(condition):

if any(condition):

# hello

22) check the occurrence of a number in the list.

print(a)   #2

23) check palindrome.

ispalindrome = name.find(name[::-1])==0
print(ispalindrome) #False
print(ispalindrome) #True

24) python threading

import threading
import time

def thread_function(name):
     print(f"Thread {name}: starting")
     print(f"Thread {name}: finishing")
my_thread = threading.Thread(target=thread_function, args=(1,))
my_second_thread = threading.Thread(target=thread_function, args=(2,))

25) Ternary Operator

sHappy = True
result_string = 'Happy' if isHappy else 'Not Happy'
print(result_string)   #Happy

26) Fizz Fuzz Program.

for i in range(100):

for i in range(100):
	if(i%3==0) {d+="fizz"}
	if(i%5==0) {d+="buzz"}

for i in range(100):
	if(c3==3) { d+="fizz"; c3=0}
	if(c5==5) { d+="buzz"; c5=0}

27) Vowel remover program

def vowel_remover(text):
    string = ""
    for l in text:
        if l.lower() != "a" and l.lower() != "e" and l.lower() != "i" and l.lower() != "o" and l.lower() != "u":
            string += l
    return string
print vowel_remover("hello world!")

28) random number and string generate.

import string
import random
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
output : #OJ2YJYKV7PKL47D

rand_str = lambda n: ''.join([random.choice(string.ascii_lowercase) for i in range(n)])
s = rand_str(10)
output: #zdszkbjryt

import random, string
def randomword(length):
   return ''.join(random.choice(string.lowercase) for i in range(length))

import random, string
def randomword(length):
   letters = string.ascii_lowercase
   return ''.join(random.choice(letters) for i in range(length))

29) external ip address program

if you needed to know what is your external ip address.

import urllib
import re

print ("we will try to open this url, in order to get IP Address")

url = ""

print (url)

request = urllib.urlopen(url).read()

theIP = re.findall(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}", request)

print ("your IP Address is: ",  theIP)

30) find a specific file in python

I will use the os.walk() and Fnmatch module function that walk in each directroy and fnmatch module matching the file names.OS.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up and its have a three tuples (dirpath,dirnames,filenames)

syntax : os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

top: each directory rooted at directory.
topdown: topdown is an optional argument it’s True or not specified. the os.walk() module scanned the directories top to down and if you set the topdown False they have scanned the directories bottom to up.
onerror: if any error comes during the execution or exception to abort the module.
followlinks : This visits of directories is pointed to by symlinks, and set to true

compile the program and scan all the directories and subdirectories bottom-to-up and showing all the file names that exist in the directories or subdirectories.

The fnmatch module is used for the wild-card pattern matching.Fnmatch compares each file against the pattern and returns a boolean value if the pattern matched then returns a True otherwise returns False. the comparison is case-sensitive then os uses a case-sensitive file system.

import os
for root, dirs, files in os.walk(".", topdown=False):
   for name in files:
      print(os.path.join(root, name))
   for name in dirs:
      print(os.path.join(root, name))

find all mp3 files in root directory path.
import fnmatch
import os
rootPath = '/'
pattern = '*.mp3'
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        print( os.path.join(root, filename))

this example filter all images files  in the system.
import fnmatch
import os

images = ['*.jpg', '*.jpeg', '*.png', '*.tif', '*.tiff']
matches = []

for root, dirnames, filenames in os.walk("C:\"):
    for extensions in images:
        for filename in fnmatch.filter(filenames, extensions):
            matches.append(os.path.join(root, filename))

lambda map filter function in python read article

Python tips and tricks topic is completed. If you like the article share it with your friends. if you have any question or query related to the article and have any suggestions please leave in the comment box.

Thanks for reading the Article.

Leave a Reply

Your email address will not be published. Required fields are marked *