Python Data Structures - Methods with Examples and Outputs
1. List Methods
l = [1, 2, 3]
l.append(4) # [1, 2, 3, 4]
l.insert(1, 99) # [1, 99, 2, 3, 4]
l.extend([5, 6]) # [1, 99, 2, 3, 4, 5, 6]
l.remove(99) # [1, 2, 3, 4, 5, 6]
l.pop() # 6, then [1, 2, 3, 4, 5]
l.index(4) #3
l.count(2) #1
l.reverse() # [5, 4, 3, 2, 1]
l.sort() # [1, 2, 3, 4, 5]
l.copy() # [1, 2, 3, 4, 5]
2. Tuple Methods
t = (1, 2, 3, 2, 4)
t.count(2) #2
t.index(3) #2
3. Set Methods
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.update([5, 6]) # {1, 2, 3, 4, 5, 6}
s.remove(3) # {1, 2, 4, 5, 6}
s.discard(10) # No error
s.pop() # Random removal
s.union({7, 8}) # {2, 4, 5, 6, 7, 8}
s.intersection({4}) # {4}
s.difference({4}) # {2, 5, 6}
s.symmetric_difference({6, 9}) # {2, 4, 5, 9}
4. Dictionary Methods
d = {'name': 'Amit', 'age': 21}
d.get('name') # Amit
d.keys() # dict_keys(['name', 'age'])
d.values() # dict_values(['Amit', 21])
d.items() # dict_items([('name', 'Amit'), ('age', 21)])
d.update({'city': 'Delhi'}) # {'name': 'Amit', 'age': 21, 'city': 'Delhi'}
d.pop('age') # 21, then {'name': 'Amit', 'city': 'Delhi'}
d.setdefault('pin', 110001) # 110001
d.copy() # {'name': 'Amit', 'city': 'Delhi', 'pin': 110001}
d.clear() # {}
5. Common Built-in Functions
l = [10, 20, 30]
len(l) #3
type(l) # <class 'list'>
sorted(l) # [10, 20, 30]
sum(l) # 60
max(l) # 30
min(l) # 10