Python Basic Tricks

#Python 1

How to check a Empty Dictionary in Python

You can easily check a python dictionary is Empty or not using bool operator. Suppose we have a dictionary dct.

  • If bool(dct) is True then dict is not Empty
  • If bool(dct) is False then dict is Empty
Check Empty Dictionary
$ dct = {}
$ bool(dct)
False
$ not dct
True

Check Not Empty Dictionary
$ dct = { "n": 10 }
$ bool(dct)
True
$ not dct
False

#Python 2

How to check a Memory Address in Python3

First consider some objects in python that we want to know their memory address:

$ a = [10,20]
$ b = 10
$ bus1 = Bus([10,20]) # instance of Bus Class

id(object):

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

$ id(-2)
10910304
$ id(-1)
10910336
$ id(0)
10910368
$ id(1)
10910400
$ id(2)
10910432
$ id(a)
139790571389000
$ id(a[0])
10910688
$ id(a[1])
10911008
$ id(b)
10910688
>>>> id(bus1)
139790562576704

hex(x):

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an index() method that returns an integer. Using hex we can easily know the address of the object reference. Some examples:

$ hex(255)
'0xff'
$ hex(-42)
'-0x2a'
$ hex(id(a))
'0x7f238759c048'
>>>> hex(id(a[0]))
'0xa67be0'
$ hex(id(a[1]))
'0xa67d20'
$ hex(id(b))
'0xa67be0'
$ hex(id(bus1))
'0x7f2386d34940'

Using object.repr() we can easily know the object memory address with type of object.

$ object.__repr__(a)
'<list object at 0x7f238759c048>'
$ object.__repr__(b)
'<int object at 0xa67be0>'
$ object.__repr__(bus1)
'<__main__.Bus object at 0x7f2386d34940>'

#Python 3

How to find frequencies of all its unique elements in Python list or string?

Using python Collection module Counter we can easily find frequencies of all its unique elements.

from collections import Counter 
s1 ='aabbbcccdeff'
c1 = Counter(s1) 
print("c1 :", c1) 
  
# Counter used in List to find frequencies of all its unique elements of list 
L1 =[1, 2, 1, 1, 4, 4, 4, 5, 6, 6, 3, 3, 0, 0] 
t1 = Counter(L1) 
  
print("t1 :", t1) 

Python Collection Counter

Note: If you have any query or any upgradation of my writing or any mistakes please comment and suggest me. You are warmly welcomed always.