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

 

Source : https://towardsdatascience.com/20-python-programming-tips-and-tricks-for-beginners-25d44db03aea

Affichages : 3004