Python functions and methods
Python functions and methods
1. String Methods
s = "hello world"
2. List Methods
lst = [3, 1, 4, 2]
• lst.append(6)
• print(lst) # [3, 1, 4, 2, 6]
• lst.insert(2, 10)
• print(lst) # [3, 1, 10, 4, 2, 6]
• lst.remove(3)
• print(lst) # [1, 10, 4, 2, 6]
• lst.sort()
• print(lst) # [1, 2, 4, 10]
• lst.reverse()
• print(lst) # [10, 4, 2, 1]
• lst.extend([7, 8])
• print(lst) # [10, 4, 2, 1, 7, 8]
• lst.clear()
• print(lst) # []
3. Tuple Methods
tup = (10, 5, 8, 5, 2)
• print(tup.count(5)) # 2 (Occurrences of 5)
• print(tup.index(8)) # 2 (Index of first 8)
• print(max(tup)) # 10
• print(min(tup)) #2
• print(len(tup)) #5
4. Dictionary Methods
• d.update({"d": 40})
• print(d) # {'a': 10, 'd': 40}
• d.clear()
• print(d) # {}
5. Set Methods
s = {4, 2, 8, 1}
• s.add(6)
• print(s) # {1, 2, 4, 6, 8}
• s.remove(2)
• print(s) # {1, 4, 6, 8}
• s.clear()
• print(s) # set()
• s1 = {1, 2, 3}
• s2 = {3, 4, 5}
• print(s1.union(s2)) # {1, 2, 3, 4, 5}
• print(s1.intersection(s2)) # {3}
• print(s1.difference(s2)) # {1, 2}
• print(s1.symmetric_difference(s2)) # {1, 2, 4, 5}
• print(max(s1)) # 3
• print(min(s1)) # 1
• print(len(s1)) # 3
Final Notes:
• Each method is in a separate line for clarity.