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) 

Output:

10 20
20 10

2. Reversing a string in Python

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

Output:

Reverse is suqedoC

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

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

Output:

Codequs For Dev

4. Chaining Of Comparison Operators.

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

Output:

True
False

5. Print The File Path Of Imported Modules.

import os 
import socket 

print(os) 
print(socket) 

Output:

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

print(MyName.Geeks) 
print(MyName.For) 
print(MyName.Geeks) 

Output:

2
1
2

7. Return Multiple Values From Functions.

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

print(a, b, c, d) 

Output:

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

Output:

4

9. Check The Memory Usage Of An Object.

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

Output:

28

10. Print string N times.

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

Output:

CodequsCodequs

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'))	 

Output:

True
False

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.

String

Trick #1 Reversing String

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

Output: Reverse is wen

Trick #2 Splitting String into multiples

a="Who Are You"
b=a.split()
print(b)

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’))

Output:
True
False

List

Trick #6 Flatten Lists

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

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

Trick #7 Reverse a list

a=[“10”,”9",”8",”7"]
print(a[::-1])

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

Trick #8 Unpack list in quick loop

a=[“10”,”9",”8",”7"]
for e in a:
    print(e)

Output:

10
9
8
7

Trick #9 Combining two lists

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

Output:

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] 
a[-3:-1] 

Output:
[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))

Output:
4

Matrix

Trick #12 Transposing a matrix

mat = [[1, 2, 3], [4, 5, 6]]
new_mat=zip(*mat)
for row in new_mat:
 print(row)

Output:

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

Operators

Trick #13 Chaining comparison operators

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

Output:

True
True
True

Dictionary

Trick #14 Inverting Dictionary

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

Output:

{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))

Output:

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}
print(z)

Output:

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

Initialization

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
listA=[0]*1000 
#listB contains 1000 2's
listB=[2]*1000

Misc

Trick #19 Check Memory Usage of An Object

import sys
a=10
print(sys.getsizeof(a))

Output: 28

Trick #20 Swapping Values

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

Output:
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
True
>>> 6 < x ≤ 8
False

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
True

You can chain more than two comparisons:

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

4. Multiple Assignment

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

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

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
2
>>> y
[4, 8]
>>> z
16

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
2
>>> y
8
>>> x, y = y, x
>>> x
8
>>> 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
'u-*-v-*-w'

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)
...
w
v
u

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]
3

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]
4

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]
3

The alternative way is probably more elegant:

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

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
44

Conclusion

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


10 Python Tips and Tricks For Writing Better Code


10 tips for learning PYTHON fast! Master Python in 2020!


5 Python tricks that will improve your life


6 Python Tips and Tricks YOU Should Know


10 cool Python Programming Tricks

#python #web-development #machine-learning

10+ Python Tips and Tricks You Should Know
115.40 GEEK