Skip to content

Instantly share code, notes, and snippets.

View ishashankkumar's full-sized avatar

Shashank Kumar ishashankkumar

View GitHub Profile
>>> a = [1, 2, 3, 4, 2, 6, 7]
>>> del a[2] # Deletes element at index 2.
>>> print a
[1, 2, 4, 2, 6, 7]
>>> del a[1:3] # Deletes elements from index upto index 3.
>>> print a
[1, 2, 6, 7]
>>> del a[:] # Deletes every content of the list.
>>> a = [1, 2, 3, 4, 2, 6, 7] # Initailized a list
>>> a.pop() # Removes the element at index -1(i.e. at last place)
7
>>> print a
[1, 2, 3, 4, 2, 6]
>>> a.pop(4) # Removes the element at index 4
2
>>> print a
[1, 2, 3, 4, 6]
>>> a.pop(100) # Index out of range.
>>> a = [1, 2, 3, 4, 2, 6, 7, 7] ##Initializaing a list
>>> a.remove(2) ##Should Remove first 2, should remove first 2.
>>> print a
[1, 3, 4, 2, 6, 7, 7]
>>> a.remove(5) . ### 5 is not part of list, should raise value error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> print a.remove(7) #### Returns None
None
>>> t1, t2 = (), (1,2,3) #Tuples
>>> sys.getsizeof(t1), sys.getsizeof(t2)
(56, 80)
>>> d1, d2, d3 = {}, {"a":1, "b":2}, {"c":3, "d":4, "e":5} #Dictionary
>>> sys.getsizeof(d1), sys.getsizeof(d2), sys.getsizeof(d3)
(280, 280, 280)
>>> l1, l2 = [], [1,2,3,4] #Lists
>>> sys.getsizeof(l1), sys.getsizeof(l2)
(72, 104)
>>> d1, d2, d3 = {}, {"a":1, "b":2}, {"c":3, "d":4, "e":5} #dictionary
>>> d1.__sizeof__(), d2.__sizeof__(), d3.__sizeof__()
(248, 248, 248)
>>> l1, l2 = [], [1,2,3,4] #list
>>> l1.__sizeof__(), l2.__sizeof__()
(40, 72)
>>> t1, t2 = (), (1,2,3) #tuple
>>> t1.__sizeof__(), t2.__sizeof__(),
(24, 48)
>>> a, b = None, '' #Empty
>>> a.__sizeof__(), b.__sizeof__()
(16, 37)
>>> a, b = 1, 1.5 # Integer, Float
>>> a.__sizeof__(), b.__sizeof__()
(24, 24)
>>> a, b = 2**63, 7561348975613048756103487563847561934857613048756139485712345678907
>>> a.__sizeof__(), b.__sizeof__()
(36, 56)
t1, t2 = (), (1,2,3) #Tuples
>>> t1.__sizeof__(), t2.__sizeof__()
(24, 48)
>>> d1, d2, d3 = {}, {"a":1, "b":2}, {"c":3, "d":4, "e":5} #Dictionary
>>> d1.__sizeof__(), d2.__sizeof__(), d3.__sizeof__()
(248, 248, 248)
# Assigning variable names to simple object types
>>> a,b,c,d,e,f = None, 1, 1.5, 2**63, 'a', 7561348975613048756103487563847561934857613048756139485712345678907
# Printing the size of these objects in memory
>>> a.__sizeof__(), b.__sizeof__(), c.__sizeof__(), d.__sizeof__(), e.__sizeof__(), f.__sizeof__()
(16, 24, 24, 36, 38, 56)
#lists, tuples, dictionary.
>>> l1, l2 = [], [1,2,3,4] #Lists
>>> l1.__sizeof__(), l2.__sizeof__()
import sys
>>> sys.getsizeof(a)
24
>>> d = 2.5
>>> sys.getsizeof(d)
24
>>> e = "sss"
>>> sys.getsizeof(e)
40
>>> id(a)
140404702868680
>>> id(c)
140404702868680
>>> id(d)
140404702868680
>>> del c
>>> sys.getrefcount(a)
3