10+ Python Tips and Tricks You Should Know

This video covers some different tips and trick in Python. These tricks make it easier and faster to write python code and give you some good tools to use the future. What’s your favorite python tip and trick? Let me know!

10 Essential Python Tips And Tricks For Programmers

Python is one of the most preferred languages out there. Its brevity and high readability makes it so popular among all programmers.
So here are few of the tips and tricks you can use to bring up your Python programming game.

1. In-Place Swapping Of Two Numbers

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


10 20
20 10

2. Reversing a string in Python

a = "GeeksForGeeks"
print("Reverse is", a[::-1]) 


Reverse is skeeGroFskeeG

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

a = ["Geeks", "For", "Geeks"] 
print(" ".join(a)) 


Geeks For Geeks

4. Chaining Of Comparison Operators.

n = 10
result = 1 < n < 20
result = 1 > n <= 9



5. Print The File Path Of Imported Modules.

import os 
import socket 



<module 'os' from '/usr/lib/python3.5/os.py'>
<module 'socket' from '/usr/lib/python3.5/socket.py'>

6. Use Of Enums In Python.

class MyName: 
	Geeks, For, Geeks = range(3) 




7. 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

8. 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)) 



9. Check The Memory Usage Of An Object.

import sys 
x = 1



10. Print string N times.

n = 2
a = "GeeksforGeeks"
print(a * n) 



11. 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('geek', 'eegk')) 
print(is_anagram('geek', 'peek'))	 



20 Python Programming Tips and Tricks for Beginners

Python Tricks For Coding More Efficiently: String, List, Dictionary, Matrix, Operators,Initialization

Python Tips and Tricks

Python is an high level general-purpose language. It’s dynamically typed and garbage-collected. It supports many programming paradigms: procedural, object-oriented, and functional. Historically, Python was conceived as a successor to the ABC language. Python strives to make developers happy by its simpler, less-cluttered syntax and grammar.

In the Zen of Python, highlights from the language philosophy includes:

  • Beautiful is better than ugly
  • Explicit is better than implicit
  • Simple is better than complex
  • Complex is better than complicated
  • Readability counts

No wonder Python’s popularity has been growing. According to Stackoverflow blog, the usage is growing more than any other language.

Python Tips and Tricks

In this article, I have compiled 20 useful Python tricks for the beginner. Whether you’ve just picked up a Python programming book or you have gone through one or two projects, some or all of these tricks may be helpful for your future projects.


Trick #1 Reversing String

print(“Reverse is”, a[::-1])

Output: Reverse is wen

Trick #2 Splitting String into multiples

a="Who Are You"

Output: [‘Who’, ‘Are’, ‘You’]

Trick #3 Printing out multiples of strings

print(“me”*8+’ ‘+”no”*10)

Output: memememememememe nononononononononono

Trick #4 Creating a single string

a = [“I”, “am”, “here”]
print(“ “.join(a))

Output: I am here

Trick #5 Check if two words are anagrams

from collections import Counter 
def is_anagram(str1, str2): 
 return Counter(str1) == Counter(str2) 
print(is_anagram(‘geek’, ‘eegk’)) 
print(is_anagram(‘geek’, ‘peek’))



Trick #6 Flatten Lists

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

Output: [1, 2, 3, 4, 5, 6]

Trick #7 Reverse a list


Output: [‘7’, ‘8’, ‘9’, ‘10’]

Trick #8 Unpack list in quick loop

for e in a:



Trick #9 Combining two lists

b=[‘e’,’f’,’g’,’h’]for x, y in zip(a, b):


a e
b f
c g
d h

Trick #10 Negative Indexing Lists

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

[8, 9]

Trick #11 Check for most frequent on the list

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



Trick #12 Transposing a matrix

mat = [[1, 2, 3], [4, 5, 6]]
for row in new_mat:


(1, 4)
(2, 5)
(3, 6)


Trick #13 Chaining comparison operators

a = 5
b = 10
c = 3
print(c < a)
print(a < b)
print(c < a < b)




Trick #14 Inverting Dictionary

dict1={‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
dict2={v: k for k, v in dict1.items()}


{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’}

Trick #15 Iterating over dictionary key and value pairs

dict1={‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
for a, b in dict1.iteritems():
 print (‘{: {}’.format(a,b))


a: 1
b: 2
c: 3
d: 4

Trick #16 Merging Dictionaries

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}


{‘a’: 1, ‘b’: 3, ‘c’: 4}


Trick #17 Initializing empty containers

a_list = list()
a_dict = dict()
a_map = map()
a_set = set()

Trick #18 Initializing List filled with some numbers

#listA contains 1000 0's
#listB contains 1000 2's


Trick #19 Check Memory Usage of An Object

import sys

Output: 28

Trick #20 Swapping Values

x, y = 1, 2
x, y = y, x
print(x, y)

2 1

20 useful Python tips and tricks you should know

Python is a popular, general-purpose, and widely used programming language. It’s used for data science and machine learning, scientific computing in many areas, back-end Web development, mobile and desktop applications, and so on. Many well-known companies use Python: Google, Dropbox, Facebook, Mozilla, IBM, Quora, Amazon, Spotify, NASA, Netflix, Reddit, and many more.

Python is free and open-source, as well as most of the products related to it. Also, it has a large, dedicated, and friendly community of programmers and other users.

Its syntax is designed with simplicity, readability, and elegance in mind.

This article presents 20 Python tips and tricks that might be useful.

1. The Zen of Python

The Zen of Python also known as PEP 20 is a small text by Tim Peters that represents the guiding principles to design and use Python. It can be found on Python Web site, but you can also get it in your terminal (console) or Jupyter notebook with a single statement:

>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

2. Chained Assignment

If you need multiple variables to reference the same object, you can use the chained assignment:

>>> x = y = z = 2
>>> x, y, z
(2, 2, 2)

Logical and elegant, right?

3. Chained Comparison

You can merge multiple comparisons to a single Python expression by chaining the comparison operators. This expression returns True if all comparisons are correct or False otherwise:

>>> x = 5
>>> 2 < x ≤ 8
>>> 6 < x ≤ 8

This is similar to (2 < x) and (x ≤ 8) and (6 < x) and (x ≤ 8), but more compact and requires x to be evaluated only once.

This is also legal:

>>> 2 < x > 4

You can chain more than two comparisons:

>>> x = 2
>>> y = 8
>>> 0 < x < 4 < y < 16

4. Multiple Assignment

You can assign multiple variables in a single statement using tuple unpacking:

>>> x, y, z = 2, 4, 8
>>> x
>>> y
>>> z

Please, note that 2, 4, 8 in the first statement is a tuple equivalent to (2, 4, 8).

5. More Advanced Multiple Assignment

Ordinary multiple assignments are not all Python can do. You don’t need the same number of elements on the left and right sides:

>>> x, *y, z = 2, 4, 8, 16
>>> x
>>> y
[4, 8]
>>> z

In this case, x takes the first value (2) because it comes first. z is the last and takes the last value (8). y takes all other values packed in a list because it has the asterisk (*y).

6. Swap Variables

You can apply multiple assignments to swap any two variables in a concise and elegant manner, without introducing the third one:

>>> x, y = 2, 8
>>> x
>>> y
>>> x, y = y, x
>>> x
>>> y 2

7. Merge Dictionaries

One way to merge two or more dictionaries is by unpacking them in a new dict:

>>> x = {'u': 1}
>>> y = {'v': 2}
>>> z = {**x, **y, 'w': 4}
>>> z
{'u': 1, 'v': 2, 'w': 4}

8. Join Strings

If you need to join multiple strings, eventually having the same character or group of characters between them, you can use str.join() method:

>>> x = ['u', 'v', 'w']
>>> y = '-*-'.join(x)
>>> y

9. Advance Iteration

If you want to iterate through a sequence and you need both sequence elements and the corresponding indices, you should use enumerate:

>>> for i, item in enumerate(['u', 'v', 'w']):
... print('index:', i, 'element:', item)
index: 0 element: u
index: 1 element: v
index: 2 element: w

In each iteration, you’ll get a tuple with the index and corresponding element of the sequence.

10. Reversed Iteration

If you want to iterate through a sequence in the reversed order, you should use reversed:

>>> for item in reversed(['u', 'v', 'w']):
... print(item)

11. Aggregate Elements

If you’re going to aggregate the elements from several sequences, you should use zip:

>>> x = [1, 2, 4]
>>> y = ('u', 'v', 'w')
>>> z = zip(x, y)
>>> z

>>> list(z)
[(1, 'u'), (2, 'v'), (4, 'w')]

You can iterate through the obtained zip object or transform it into a list or tuple.

12. Transpose Matrices

Although people usually apply NumPy (or similar libraries) when working with matrices, you can obtain the transpose of a matrix with zip:

>>> x = [(1, 2, 4), ('u', 'v', 'w')]
>>> y = zip(*x)
>>> z = list(y)
>>> z
[(1, 'u'), (2, 'v'), (4, 'w')]

13. Unique Values

You can remove duplicates from a list, that is obtained unique values by converting it to a set if the order of elements is not important:

>>> x = [1, 2, 1, 4, 8]
>>> y = set(x)
>>> y
{8, 1, 2, 4}
>>> z = list(y)
>>> z
[8, 1, 2, 4]

14. Sort Sequences

Sequences are sorted by their first elements by default:

>>> x = (1, 'v')
>>> y = (4, 'u')
>>> z = (2, 'w')
>>> sorted([x, y, z])
[(1, 'v'), (2, 'w'), (4, 'u')]

However, if you want to sort them according to their second (or other) elements, you can use the parameter key and an appropriate lambda function as the corresponding argument:

>>> sorted([x, y, z], key=lambda item: item[1])
[(4, 'u'), (1, 'v'), (2, 'w')]

It’s similar if you want to obtain the reversed order:

>>> sorted([x, y, z], key=lambda item: item[1], reverse=True)
[(2, 'w'), (1, 'v'), (4, 'u')]

15. Sort Dictionaries

You can use a similar approach to sort key-value tuples of dictionaries obtained with .items() method:

>>> x = {'u': 4, 'w': 2, 'v': 1}
>>> sorted(x.items())
[('u', 4), ('v', 1), ('w', 2)]

They are sorted according to the keys. If you want to them to be sorted according to their values, you should specify the arguments that correspond to key and eventually reverse:

>>> sorted(x.items(), key=lambda item: item[1])
[('v', 1), ('w', 2), ('u', 4)]
>>> sorted(x.items(), key=lambda item: item[1], reverse=True)
[('u', 4), ('w', 2), ('v', 1)]

16. Raw Formatted Strings

PEP 498 and Python 3.6 introduced so-called formatted strings or f-strings. You can embed expressions inside such strings. It’s possible and straightforward to treat a string as both raw and formatted. You need to include both prefixes: fr.

>>> fr'u \ n v w={2 + 8}'
'u \\ n v w=10'

17. Obtain Current Date and Time

Python has a built-in module datetime that is versatile in working with dates and times. One of its methods, .now(), returns the current date and time:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2019, 5, 20, 1, 12, 31, 230217)

18. Obtain the Index of the Maximal (or Minimal) Element

Python doesn’t provide a routine to directly get the index of the maximal or minimal element in a list or tuple. Fortunately, there are (at least) two elegant ways to do so:

>>> x = [2, 1, 4, 16, 8]
>>> max((item, i) for i, item in enumerate(x))[1]

If there are two or more elements with the maximal value, this approach returns the index of the last one:

>>> y = [2, 1, 4, 8, 8]
>>> max((item, i) for i, item in enumerate(y))[1]

To get the index of the first occurrence, you need to change the previous statement slightly:

>>> -max((item, -i) for i, item in enumerate(y))[1]

The alternative way is probably more elegant:

>>> x = [2, 1, 4, 16, 8]
>>> max(range(len(x)), key=lambda i: x[i])
>>> y = [2, 1, 4, 8, 8]
>>> max(range(len(y)), key=lambda i: x[i])

To find the index of the minimal element, use the function min instead of max.

19. Obtain the Cartesian Product

The built-in module itertools provides many potentially useful classes. One of them is a product used to obtain the Cartesian product:

>>> import itertools
>>> x, y, z = (2, 8), ['u', 'v', 'w'], {True, False}
>>> list(itertools.product(x, y, z))
[(2, 'u', False), (2, 'u', True), (2, 'v', False), (2, 'v', True),
(2, 'w', False), (2, 'w', True), (8, 'u', False), (8, 'u', True),
(8, 'v', False), (8, 'v', True), (8, 'w', False), (8, 'w', True)]

20. The Operator for Matrix Multiplication

PEP 465 and Python 3.5 introduced the dedicated infix operator for matrix multiplication @. You can implement it for your class with the methods matmul, rmatmul, and imatmul. This is how elegant the code for multiplying vectors or matrices looks like:

>>> import numpy as np
>>> x, y = np.array([1, 3, 5]), np.array([2, 4, 6])
>>> z = x @ y
>>> z


You’ve seen 20 Python tips and tricks that make it interesting and elegant. There are many other language features worth exploring.


#python #web-development #machine-learning

What is GEEK

Buddha Community

10+ Python Tips and Tricks You Should Know

pallavi patil


Your article is too good and informative. I am searching for same blog and I get the exact article I am thankful to you for sharing this educational article. and the way you wrote is also good, you covered up all the points which I searching for & I am impressed by reading this article. Keep writing and sharing educational article like this which can help us to grow our knowledge.
python classes in pune
software testing course in pune

Art  Lind

Art Lind


Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Shardul Bhatt

Shardul Bhatt


Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.


Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Art  Lind

Art Lind


How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.


In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…

You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.

1. init

class AnyClass:
    def __init__():
        print("Init called on its own")
obj = AnyClass()

The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.

The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.

Init called on its own

2. add

Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,

class AnyClass:
    def __init__(self, var):
        self.some_var = var
    def __add__(self, other_obj):
        print("Calling the add method")
        return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2

#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python

Virgil  Hagenes

Virgil Hagenes


The Basics of Python OS Module

The** OS module** is a python module that provides the interface for interacting with the underlying operating system that Python is running.

This module provides a portable way of using **operating system **dependent functionality.

OS module comes by default on Python’s standard utility modules therefore you don’t need to install anything to start using it

OS module provides a ton of** methods** of which you use in variety of situation in **interacting **with the operating system ranging from_ creating new file & folder_s to renaming and _deleting t_hem.

You can view all of them by using dir() as shown below

>>>import os 
'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 
'cpu_count', 'ctermid', 'curdir', 'defpath', 'device_encoding', 
'posix_fallocate', 'pread', 'putenv', 'pwrite', 'read', 'readlink', 
'readv', 'remove', 'removedirs', 'removexattr', 'rename', 'renames'
............................and so on...........................

On this tutorial We will just check some of methods on OS Module

os.getcwd ( )

This OS method is used to get the path of the current working directory.

>>>import os 
>>>os.getcwd() #getting path of current directory

#python #python-programming #python-tutorials #learn-python #python-tips #python-developers #python3