Novonto Agency

Novonto Agency

Python tricks 101

Python tips which are relatively uncommon and are very useful.

Swapping values

#! /usr/bin/env python3
"""pythonic way of calue swapping"""
a, b = 5,10
print(a, b)
a, b = b, a
print(a, b

Create a single string from all the elements in list

#! /usr/bin/env python3
a = ["Python", "is", "awesome"]
print(" ".join(a))

Find The Most Frequent Value In A List.

#! /usr/bin/env python3
""" most frequent element in a list"""
a = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(a), key = a.count))

Checking if two words are anagrams

#! /usr/bin/env python3
from collections import Counter
Counter(str1) == Counter(str2)

Reverse a String

#! /usr/bin/env python3
"""reversing string with special case of slice step param"""
a = 'abcdefghijklmnopqrstuvwxyz'
print(a[::-1])
"""iterating over string contents in reverse efficiently."""
for char in reversed(a):
    print(char)
"""reversing an integer through type conversion and slicing."""
num = 123456789
print(int(str(num)[::-1]))

Reverse a list

#! /usr/bin/env python3
"""reversing list with special case of slice step param"""
a = [5, 4, 3, 2, 1]
print(a[::-1])
"""iterating over list contents in reverse efficiently."""
for ele in reversed(a):
    print(ele)

Transpose 2d array

#! /usr/bin/env python3
"""transpose 2d array [[a,b], [c,d], [e,f]] -> [[a,c,e], [b,d,f]]"""
original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*original)
print(list(transposed))

Chained Comparison

#! /usr/bin/env python3
"""chained comparison with all kind of operators"""
a = 10
print(1 < a < 50)
print(10 == a < 20)

Chained function call

#! /usr/bin/env python3
"""calling different functions with same arguments based on condition"""
def product(a, b):
    return a * b
    
def add(a, b):
    return a + b
    
b = True
print((product if b else add)(5, 7))

Copying List

#! /usr/bin/env python3
import sys
"""a fast way to make a shallow copy of a list"""
a = [1, 2, 3, 4, 5]
print(a[:])
"""adding an empty list yields a copy of initial list"""
a = [1, 2, 3, 4, 5]
print(a + [])  # in python3, for small lists performs faster than a[:]
"""copy list by typecasting method"""
a = [1, 2, 3, 4, 5]
print(list(a))
"""using the list.copy() method (python3 only)"""
if sys.version_info.major == 3:
    a = [1, 2, 3, 4, 5]
    print(a.copy())
else:
    # in python2 there exists the `copy` builtin module
    from copy import copy
    a = [1, 2, 3, 4, 5]
    print(copy(a))
"""copy nested lists using copy.deepcopy"""
from copy import deepcopy
l = [[1, 2], [3, 4]]
l2 = deepcopy(l)
print(l2)

Dictionary Get

#! /usr/bin/env python3
"""returning None or default value, when key is not in dict"""
d = {'a': 1, 'b': 2}
print(d.get('c', 3))

Sort Dictionary by Value

#!/usr/bin/env python3
""" Sort a dictionary by its values with the built-in sorted() function and a 'key' argument. """
 
d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1}
print(sorted(d.items(), key=lambda x: x[1]))
""" Sort using operator.itemgetter as the sort key instead of a lambda"""
from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))
"""Sort dict keys by value"""
print(sorted(d, key=d.get))

For Else

#! /usr/bin/env python3
"""else gets called when for loop does not reach break statement"""
a = [1, 2, 3, 4, 5]
for el in a:
    if el == 0:
        break
else:
    print('did not break out of for loop')

Convert list to comma separated

#! /usr/bin/env python3
"""converts list to comma separated string"""
items = ['foo', 'bar', 'xyz']
print (','.join(items))
"""list of numbers to comma separated"""
numbers = [2, 3, 5, 10]
print (','.join(map(str, numbers)))
"""list of mix  data"""
data = [2, 'hello', 3, 3.4]
print (','.join(map(str, data)))

Merge dict’s

#! /usr/bin/env python3
"""merge dict's"""
d1 = {'a': 1}
d2 = {'b': 2}
# python 3.5
print ({**d1, **d2})
print(dict(d1.items() | d2.items()))
d1.update(d2)
print(d1)

Min and Max index in List

#! /usr/bin/env python3
"""
Find Index of Min/Max Element.
"""
lst = [40, 10, 20, 30]
def minIndex(lst):
    return min(range(len(lst)), key=lst.__getitem__)  # use xrange if < 2.7
def maxIndex(lst):
    return max(range(len(lst)), key=lst.__getitem__)  # use xrange if < 2.7
print(minIndex(lst))
print(maxIndex(lst))

Remove duplicates from a list

#! /usr/bin/env python3
"""remove duplicate items from list. note: does not preserve the original list order"""
items = [2, 2, 3, 3, 1]
newitems2 = list(set(items))
print(newitems2)
"""remove dups and keep order"""
from collections import OrderedDict
items = ["foo", "bar", "bar", "foo"]
print(list(OrderedDict.fromkeys(items).keys()))

More Info

Want more tricks look at the PyTricks github page
Want to know how to create these beautiful screenshots? We got you covered, read it here

COMMENT
NAME
EMAIL

Back to top: