20 Python Programming Tips and Tricks for Beginners

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

@nitram509 unsplash.com

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.

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