Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Vrundesha Joshi

In this article, we are going to cover some useful python tricks and tips that will come handy when you are writing program in competitive programming or for your company as they reduce the code and optimized execution.

In-Place Swapping of two Numbers

x, y = 50, 70
print(x, y)

#swapping
x, y = y, x
print(x, y)

Output

50 70
70 50

Creating a single string from a list

lst = ['What', 'a', 'fine', 'morning']
print(" ".join(lst))

Output

What a fine morning

Remove duplicates from a list

# Remove duplicates from a list

#This method will not preserve the order
lst = [2, 4, 4 ,9 , 13, 4, 2]
print("Original list: ", lst)
new_lst = list(set(lst))
print(new_lst)

# Below method will preserve the order
from collections import OrderedDict
lst = [2, 4, 4 ,9 , 13, 4, 2]
print(list(OrderedDict.fromkeys(lst).keys()))

Output

Original list: [2, 4, 4, 9, 13, 4, 2]
[9, 2, 4, 13]
[2, 4, 9, 13]

Reverse a string

#Reverse a string
s = "Hello, World!"
print(s[::-1])

letters = ("abcdefghijklmnopqrstuvwxyz")
print(letters[::-1])

Output

!dlroW ,olleH
Zyxwvutsrqponmlkjihgfedcba

Reversing a list

# Reversing a list

lst = [20, 40 , 60, 80]
print(lst[::-1])

Output

[80, 60, 40, 20]

Transpose two-dimensional array

#Transpose of a 2d array, that means if the matrix is 2 * 3 after transpose it will be 3* 2 matrix.

matrix = [['a', 'b', 'c'], ['d', 'e', 'f']]
transMatrix = zip (*matrix)
print(list (transMatrix))

Output

[('a', 'd'), ('b', 'e'), ('c', 'f')]

Check if two strings are anagrams

#Check if two strings are anagrams

from collections import Counter

def is_anagram (str1, str2):
return Counter(str1) == Counter(str2)

print(is_anagram('hello', 'ollhe'))
#and
print(is_anagram('Hello', 'hello'))

Output

True
False

Inspect an object in python

#Inspect an object in pyton

lst =[1, 3, 4, 7, 9]
print(dir(lst))

Output

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Enumerate a list

#Enumerate a list
lst = [20, 10, 40, 50 , 30, 40]
for i, value in enumerate(lst):
print(i, ': ', value)

Output

0 : 20
1 : 10
2 : 40
3 : 50
4 : 30
5 : 40

Factorial of any number

#Factorial of any number

import functools

result = (lambda s: functools.reduce(int. __mul__, range(1, s+1), 1))(5)
print(result)

Output

120

Creating a dictionary from two related sequences

#Creating a dictionary from two related sequences
x1 = ('Name', 'EmpId', 'Sector')
y1 = ('Zack', 4005, 'Finance')
print(dict (zip(x1, y1)))

Output

{'Name': 'Zack', 'EmpId': 4005, 'Sector': 'Finance'}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.