
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Essential Python Tips and Tricks for Programmers
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.
Get n largest elements in a list using the module heapq
Example
import heapq marks = [91, 67, 34, 56, 78, 99, 87, 23, 78, 66] print("Marks = ",marks) print("Largest =",heapq.nlargest(2, marks))
Output
Marks = [91, 67, 34, 56, 78, 99, 87, 23, 78, 66] Largest = [99, 91]
Get n smallest elements in a list using the module heapq
Example
import heapq marks = [91, 67, 34, 56, 78, 99, 87, 23, 78, 66] print("Marks = ",marks) print("Smallest =",heapq.nsmallest(2, marks))
Output
Marks = [91, 67, 34, 56, 78, 99, 87, 23, 78, 66] Smallest = [23, 34]
Creating a single string from a list
Example
myList = ['Hello', 'World'] print(" ".join(myList))
Output
Hello World
Assign multiple variables in a single line
Example
a, b, c = 10, 20, 30 print(a, b, c)
Output
10 20 30
Loop through the elements in a list in a single line: List comprehensions
Example
myList = [5, 12, 15, 18, 24, 32, 55, 65] res = [number for number in myList if number % 5 == 0] print("Displaying numbers divisible by 5 = ",res)
Output
Displaying numbers divisible by 5 = [5, 15, 55, 65]
In-Place Swapping of two Numbers
Example
a, b = 50, 70 print("Before Swapping = ",a, b) # swapping a, b = b, a print("After Swapping = ",a, b)
Output
Before Swapping = 50 70 After Swapping = 70 50
Reverse a string in a single line
Example
# Reverse a string myStr = "This is it!!!" print("String = ",myStr) print("Reversed String = ",myStr[::-1])
Output
String = This is it!!! Reversed String = !!!ti si sihT
Creating a dictionary from two related sequences
Example
# Creating a dictionary from two related sequences s1 = ('Name', 'EmpId', 'Dept') r1 = ('Jones', 767, 'Marketing') print(dict (zip(s1, r1)))
Output
{'Name': 'Jones', 'EmpId': 767, 'Dept': 'Marketing'}
Inspect an object in python
Example
# Inspect an object in Python myList =[1, 3, 4, 7, 9] print(dir(myList))
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']
Advertisements