Python
Methods Examples
By
[Link]
@coding_cave.hq
Python methods @coding_cave
The most used methods in python with string, list[ ], set{ }, tuple( ),
and dictionary{:}
string
1. upper() 8. capitalize()
2. lower() 9. find()
3. strip() 10. count()
4. replace() 11. startswith()
5. split() 12. endswith()
6. join() 13. isalpha()
7. title() 14. isdigit()
15. isalnam()
1. upper() : Converts all characters in the string to uppercase.
text = "hello world"
upper_text = [Link]()
print(upper_text) HELLO WORLD
2. lower() : Converts all characters in the string to lowercase.
text = "HELLO WORLD"
lower_text = [Link]()
print(lower_text) hello world
2
Python methods @coding_cave
3. strip() : Removes leading and trailing whitespace (or specified
characters).
text = " hello world "
result = [Link]()
print(result) hello world
text = "!!!hello world!!!"
result = [Link]("!")
print(result) hello world
4. replace(old, new) : Replaces occurrences of a substring within
the string with another substring.
text = "hello world"
result = [Link]("hello", "hi")
print(result) hi world
5. split(separator) : Splits the string into a list of substrings based
on a specified separator.
text = "hello world"
result = [Link](" ")
print(result) ["hello", "world"]
3
Python methods @coding_cave
6. join(iterable) : Joins elements of an iterable (like a list) into a
single string, with a specified separator.
words = ["hello", "world"]
result = " ".join(words)
print(result) hello world
7. title() : Converts the first character of each word to uppercase
and the rest to lowercase.
text = "hello world"
result = [Link]()
print(result) Hello World
8. capitalize() : Capitalizes the first character of the string.
text = "hello world"
result = [Link]()
print(result) Hello world
9. find(substring) : Returns the index of the first occurrence of a
substring, or -1 if not found.
text = "hello world"
result = [Link]("world")
print(result) 6
4
Python methods @coding_cave
10. count(substring) : Returns the number of occurrences of a
substring in the string.
text = "hello world, hello Python"
result = [Link]("hello")
print(result) 2
11. startswith(prefix) : Checks if the string starts with a specified
prefix. Returns True or False.
text = "hello world"
result = [Link]("hello")
print(result) True
12. endswith(suffix) : Checks if the string ends with a specified
suffix. Returns True or False.
text = "hello world"
result = [Link]("world")
print(result) True
5
Python methods @coding_cave
13. isalpha() : Checks if all characters in the string are alphabetic.
Returns True or False.
text = "hello"
result = [Link]()
print(result) True
14. isdigit () : Checks if all characters in the string are digits.
Returns True or False.
text = "12345"
result = [Link]()
print(result) True
15. isalnum () : Checks if all characters in the string are
alphanumeric (letters and numbers). Returns True or False.
text = "hello"
result = [Link]()
print(result) True
6
Python methods @coding_cave
list[ ]
1. append( ) 6. clear( )
2. extend( ) 7. copy( )
3. insert( ) 8. count( )
4. remove( ) 9. index( )
5. pop( ) 10 . reverse( )
11 . sort( )
1. append() : Add an element to the end of the list.
my_list = [10, 20, 30]
my_list.append(40)
print(my_list) [10, 20, 30, 40]
2. extend() : Extend the list by appending elements from another
list.
my_list = [10, 20, 30]
my_list.extend([40, 50])
print(my_list) [10, 20, 30, 40, 50]
7
Python methods @coding_cave
3. insert() : Insert an element at a specific position.
my_list = [10, 20, 30]
my_list.insert(2, 25)
print(my_list) [10, 20, 25, 30]
4. remove() : Remove the first occurrence of a specific element.
my_list = [10, 20, 30]
my_list. remove(30)
[10, 20]
print(my_list)
5. pop() : Remove and return the element at a specific position (or
the last element if no position is specified).
my_list = [10, 20, 30]
popped_element = my_list.pop(1)
print(my_list)
[10, 30]
print("Popped element:", popped_element) Popped element: 20
6. clear() : Remove all elements from the list.
my_list = [10, 20, 30]
my_list.clear()
After clear(): [ ]
print("After clear():", my_list)
8
Python methods @coding_cave
7. copy() : Create a shallow copy of the list.
my_list = [10, 20, 30]
my_list_copy = my_list.copy()
print("Copy of the list:", my_list_copy) Copy of the list: [10, 20, 30]
8. count() : Count the number of occurrences of a specific
element.
my_list = [10, 20, 30, 20]
count_20 = my_list.count(20)
print("Count of 20 in the list:", count_20) Count of 20 in the list: 2
9. index() : Find the index of the first occurrence of a specific
element.
my_list = [10, 20, 30]
index_of_30 = my_list.index(30)
print("Index of 30:", index_of_30) Index of 30: 2
9
Python methods @coding_cave
10. reverse() : Reverse the order of the list.
my_list = [10, 20, 30]
my_list.reverse()
print("After reverse():", my_list) After reverse(): [30, 20, 10]
11. sort() : Sort the list in ascending order.
my_list = [10, 40, 30, 20]
my_list.sort()
print("After sort():", my_list)) After sort(): [10, 20, 30, 40]
10
Python methods @coding_cave
set{ }
1. add() 8. difference()
2. update() 9. difference_update()
3. remove() 10. intersection()
4. pop() 11. intersection_update()
5. clear() 12. isdisjoint()
6. discard() 13. issubset()
7. copy() 14. issuperset()
15. union()
1. add() : Add an element to the end of the set.
my_set = {1, 2, 3}
my_set.add(4)
print("After add(4):", my_set) After add(4): {1, 2, 3, 4}
2. update() : Update the set, adding elements from another set or
iterable.
my_set = {1, 2, 3}
my_set.update([4, 5])
print("After update([4, 5]):", my_set) After update([4, 5]): {1, 2, 3, 4, 5}
11
Python methods @coding_cave
3. remove() : Remove a specific element from the set (raises Key-
Error if not found).
my_set = {1, 2, 3}
my_set.remove(2)
print("After remove(2):", my_set) After remove(2): {1, 3}
4. pop() : Remove and return an arbitrary element from the set.
my_set = {1, 2, 3}
popped_element = my_set.pop()
print("After pop():", my_set) After pop(): {2, 3}
print("Popped element:", popped_element) Popped element: 1
5. clear() : Remove all elements from the set.
my_set = {1, 2, 3}
my_set.clear()
After clear(): set()
print("After clear():", my_set)
6. discard() : Remove a specific element from the set (does not
raise an error if not found).
my_set = {1, 2, 3}
my_set.discard(3)
After discard(3): {1, 2}
print("After discard(3):", my_set)
12
Python methods @coding_cave
7. copy() : Create a shallow copy of the set.
my_set = {1, 2, 3}
my_set_copy = my_set.copy()
Copy of the set: {1, 2, 3}
print("Copy of the set:", my_set_copy)
8. difference() : Return the difference of two sets as a new set.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
diff_set = [Link](set2)
print("Difference between set1and set2:", diff_set)
Difference between set1and set2: {1, 2, 3}
9. difference_update(): Remove elements found in another set.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
set1.difference_update(set2)
print("After difference_update(set2):", set1)
After difference_update(set2): {1, 2, 3}
The difference between difference() & difference_update()
difference() difference_update()
Return the difference of Remove elements found in
two sets as a new set another set
13
Python methods @coding_cave
10. intersection(): Return the intersection of two sets as a new set.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
intersection_set = [Link](set2)
print("Intersection of set1 and set2:", intersection_set)
Intersection of set1 and set2: {4, 5}
11. intersection_update(): Update the set with the intersection of
itself and another.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
set1.intersection_update(set2)
print("After intersection_update(set2):", set1)
After intersection_update(set2): {4, 5}
The difference between intersection () & intersection _update()
intersection () intersection _update()
Return the intersection of two Update the set with the
sets as a new set intersection of itself and
another
14
Python methods @coding_cave
12. isdisjoint() : Return True if two sets have a null intersection.
set1 = {1, 2, 3}
set2 = {4, 5}
disjoint = [Link](set2)
Is set1 disjoint with set2?: True
print("Is set1 disjoint with set2?:", disjoint)
13. issubset() : Return True if the set is a subset of another set.
set1 = {1, 2, 3}
subset_result = [Link]({1, 2, 3, 4, 5})
print("Is set1 a subset?:", subset_result) Is set1 a subset?: True
14. issuperset() : Return True if the set is a superset of another set.
set1 = {1, 2, 3}
superset_result = {1, 2, 3, 4, 5}.issuperset(set1)
print("Is {1, 2, 3, 4, 5} a superset of set1?:", superset_result)
Is {1, 2, 3, 4, 5} a superset of set1?: True
15. union() : Return the union of two sets as a new set.
set1 = {1, 2, 3}
set2 = {4, 5}
union_set = [Link](set2)
print("Union of set1 and set2:", union_set) Union of set1 and set2: {1, 2, 3, 4, 5}
15
Python methods @coding_cave
tuple( )
1. count()
2. index()
1. count() : Returns the number of occurrences of a specified
element in the tuple.
my_tuple = (1, 2, 2, 3, 4, 2)
count_of_2 = my_tuple.count(2)
print("Number of occurrences of 2:", count_of_2)
Number of occurrences of 2: 3
2. index() : Returns the index of the first occurrence of a specified
element in the tuple.
my_tuple = (1, 2, 3, 4, 5)
index_of_3 = my_tuple.index(3)
print("Index of 3:", index_of_3) # Output: 2
Index of 3: 2
16
Python methods @coding_cave
Dictionary{key : value }
1. update() 6. values()
2. copy() 7. clear()
3. get() 8. pop()
4. items() 9. popitem()
5. keys() 10. setdefault()
11. fromkeys()
1. update() : Updates the dictionary with elements from another
dictionary or from an iterable of key-value pairs.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
[Link](dict2)
print(dict1)
{'a': 1, 'b': 3, 'c': 4}
2. copy() : Returns a shallow copy of the dictionary.
original_dict = {'a': 1, 'b': 2}
copied_dict = original_dict.copy()
print(copied_dict
{'a': 1, 'b': 2}
17
Python methods @coding_cave
3. get() : Returns the value for a specified key if the key is in the
dictionary, otherwise returns None (or a specified default value).
my_dict = {'a': 1, 'b': 2}
print(my_dict.get('a'))
print(my_dict.get('c', 'Not Found')) 1
Not Found
4. items() : Returns a view object that displays a list of a
dictionary's key-value tuple pairs.
my_dict = {'a': 1, 'b': 2}
print(my_dict.items()) dict_items([('a', 1), ('b', 2)])
5. keys() : Returns a view object that displays a list of all the keys
in the dictionary.
my_dict = {'a': 1, 'b': 2}
print(my_dict.keys()) dict_keys(['a', 'b'])
6. values() : Returns a view object that displays a list of all the
values in the dictionary.
my_dict = {'a': 1, 'b': 2}
print(my_dict.values()) dict_values([1, 2])
18
Python methods @coding_cave
7. clear() : Removes all elements from the dictionary, leaving it
empty.
my_dict = {'a': 1, 'b': 2}
my_dict.clear()
{}
print(my_dict)
8. pop() : Removes the specified key and returns the corresponding value. If
the key is not found, it returns the default value if provided, otherwise
raises a KeyError.
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print(value) 2
print(my_dict) {'a': 1, 'c': 3}
9. popitem() : Removes and returns the last key-value pair from the
dictionary. In Python 3.7 and later, dictionaries are ordered, so this removes
the last inserted item.
my_dict = {'a': 1, 'b': 2, 'c': 3}
item = my_dict.popitem()
print(item)
('c', 3)
print(my_dict)
{'a': 1, 'b': 2}
19
Python methods @coding_cave
10. setdefault() : Returns the value of a key if it is in the
dictionary. If not, it inserts the key with a specified value.
my_dict = {'a': 1, 'b': 2}
value = my_dict.setdefault('c', 3)
print(value)
3
print(my_dict)
{'a': 1, 'b': 2, 'c': 3}
11. fromkeys() : Creates a new dictionary from a given sequence
of keys, with all values set to a specified value.
keys = ['a', 'b', 'c']
new_dict = [Link](keys, 0)
print(new_dict)
{'a': 0, 'b': 0, 'c': 0}
By
[Link]
20