0% found this document useful (0 votes)
2 views15 pages

Essential Python Methods

The document outlines essential Python methods for lists, sets, dictionaries, and strings, providing descriptions, code examples, and expected outputs for each method. It covers methods such as append, clear, copy, and sort for lists; add, remove, and union for sets; and clear, copy, and update for dictionaries. Additionally, it includes string methods like capitalize, count, and format, making it a comprehensive guide for developers to reference.

Uploaded by

Ghivvago
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Essential Python Methods

The document outlines essential Python methods for lists, sets, dictionaries, and strings, providing descriptions, code examples, and expected outputs for each method. It covers methods such as append, clear, copy, and sort for lists; add, remove, and union for sets; and clear, copy, and update for dictionaries. Additionally, it includes string methods like capitalize, count, and format, making it a comprehensive guide for developers to reference.

Uploaded by

Ghivvago
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ESSENTIAL PYTHON METHODS

EVERY DEVELOPER SHOULD KNOW


LIST METHODS
Method Description Code Example Output

numbers = [1, 2, 3]
append() Adds an element at the end of the list. [1, 2, 3, 4]
[Link](4)

numbers = [1, 2, 3]
clear() Removes all the elements from the list. []
[Link]()

numbers = [1, 2, 3]
copy() Returns a shallow copy of the list. [1, 2, 3]
new_list = [Link]()

Returns the number of occurrences of a numbers = [1, 2, 2, 2, 3]


count() 3
specified value. print([Link](2))

Adds elements of an iterable (like numbers = [1, 2, 3]


extend() [1, 2, 3, 4, 5]
another list) to the end of the list. [Link]([4, 5])

Returns the index of the first occurrence numbers = [10, 20, 30, 20]
index() 1
of a specified value. print([Link](20))

Inserts an element at a specified numbers = [1, 2, 4]


insert() [1, 2, 3, 4]
position. [Link](2, 3)

Removes and returns the element at a numbers = [1, 2, 3, 4]


pop() [1, 2, 3]
specified position (default is last). [Link]()

Removes the first occurrence of a numbers= [1, 2, 3, 2]


remove() [1, 3, 2]
specified value. [Link](2)

numbers = [1, 2, 3]
reverse() Reverses the order of the list in place. [3, 2, 1]
[Link]()

Sorts the list in ascending order (or numbers = [3, 1, 4, 2]


sort() [1, 2, 3, 4]
based on a custom function). [Link]()

[Link]
SET METHODS
Method Description Code Example Output

set1 = {1, 2, 3}
add() Inserts an element into the set. {1, 2, 3, 4}
[Link](4)

Removes all elements, leaving set1 = {1, 2, 3}


clear() set()
the set empty. [Link]()

Creates and returns a duplicate set1 = {1, 2, 3}


copy() {1, 2, 3}
of the set. set2 = [Link]()

set1 = {1, 2, 3}
Returns elements present in one
difference() set2 = {3, 4, 5} {1, 2}
set but not in another.
[Link](set2)

set1 = {1, 2, 3}
difference_up Removes elements found in
set2 = {2, 3, 4} {1}
date() another set from the current set.
set1.difference_update(set2)

Removes a specified element if it set1 = {1, 2, 3}


discard() {1, 3}
exists; no error if absent. [Link](2)

set1 = {1, 2, 3}
Returns elements common to
intersection() set2 = {2, 3, 4} {2, 3}
multiple sets.
[Link](set2)

set1 = {1, 2, 3}
intersection_ Updates the set with elements
set2 = {2, 3, 4} {2, 3}
update() common to all sets.
set1.intersection_update(set2)

set1 = {1, 2, 3}
Returns True if two sets have no
isdisjoint() set2 = {4, 5, 6} True
elements in common.
[Link](set2)

set1 = {1, 2}
Checks if all elements of one set
issubset() set2 = {1, 2, 3, 4} True
are in another.
[Link](set2)

set1 = {1, 2, 3, 4}
Checks if the current set
issuperset() set2 = {1, 2} True
contains all elements of another.
[Link](set2)

[Link]
SET METHODS
Method Description Code Example Output

Removes and returns an (Random element


set1 = {10, 20, 30}
pop() arbitrary element from the removed, e.g.,) 10
[Link]())
set. and {20, 30}

Deletes a specified element; set1 = {1, 2, 3}


remove() {1, 3}
raises an error if not found. [Link](2)

set1 = {1, 2, 3}
symmetric_ Returns elements unique to
set2 = {3, 4, 5} {1, 2, 4, 5}
difference() each set (not in both).
set1.symmetric_difference(set2)

symmetric_ Updates the set with set1 = {1, 2, 3}


difference_ elements unique to either set2 = {3, 4, 5} {1, 2, 4, 5}
update() set. set1.symmetric_difference_update(set2)

set1 = {1, 2, 3}
Returns all elements from
union() set2 = {3, 4, 5} {1, 2, 3, 4, 5}
both sets without duplicates.
[Link](set2)

Adds all elements from set1 = {1, 2, 3}


update() another set to the current set2 = {4, 5} {1, 2, 3, 4, 5}
one. [Link](set2)

[Link]
DICTIONARY METHODS
Method Description Code Example Output

Deletes all key-value pairs, dict1 = {'a': 1, 'b': 2, 'c': 3}


clear() {}
making the dictionary empty. [Link]()

Creates and returns a duplicate dict1 = {'x': 10, 'y': 20}


copy() {'x': 10, 'y': 20}
of the dictionary. dict2 = [Link]()

Creates a new dictionary with keys = ['a', 'b', 'c']


fromkeys() specified keys, assigning a dict1 = [Link](keys, 0) {'a': 0, 'b': 0, 'c': 0}
common default value. print(dict1)

Retrieves the value associated dict1 = {'a': 1, 'b': 2}


get() with a key; returns None if the print([Link]('b')) 2 and None
key is absent. print([Link]('c'))

Returns all dictionary entries as dict_items([('a', 1),


items() dict1 = {'a': 1, 'b': 2} [Link]()
key-value tuple pairs. ('b', 2)])

Provides a view containing all the dict1 = {'a': 1, 'b': 2, 'c': 3}


keys() dict_keys(['a', 'b', 'c'])
keys in the dictionary. print([Link]())

dict1 = {'a': 1, 'b': 2, 'c': 3}


Removes a key-value pair by key
pop() print([Link]('b')) 2 and {'a': 1, 'c': 3}
and returns its value.
print(dict1)

dict1 = {'a': 1, 'b': 2, 'c': 3}


Removes and returns the most ('c', 3) and
popitem() print([Link]())
recently added key-value pair. {'a': 1, 'b': 2}
print(dict1)

Returns the value of a key; if dict1 = {'a': 1, 'b': 2}


2, 5, and
setdefault() missing, inserts it with a print([Link]('b', 5))
{'a': 1, 'b': 2, 'c': 5}
specified default. print([Link]('c', 5))

Merges another dictionary or dict1 = {'a': 1, 'b': 2}


iterable into the existing dict2 = {'b': 3, 'c': 4}
update() {'a': 1, 'b': 3, 'c': 4}
dictionary, updating keys if they [Link](dict2)
exist. print(dict1)

Returns a view object containing dict1 = {'x': 10, 'y': 20, 'z': 30} dict_values([10, 20,
values()
all dictionary values. print([Link]()) 30])

[Link]
DICTIONARY METHODS
Method Description Code Example Output

Deletes all key-value pairs, dict1 = {'a': 1, 'b': 2, 'c': 3}


clear() {}
making the dictionary empty. [Link]()

Creates and returns a duplicate dict1 = {'x': 10, 'y': 20}


copy() {'x': 10, 'y': 20}
of the dictionary. dict2 = [Link]()

Creates a new dictionary with keys = ['a', 'b', 'c']


fromkeys() specified keys, assigning a dict1 = [Link](keys, 0) {'a': 0, 'b': 0, 'c': 0}
common default value. print(dict1)

Retrieves the value associated dict1 = {'a': 1, 'b': 2}


get() with a key; returns None if the print([Link]('b')) 2 and None
key is absent. print([Link]('c'))

Returns all dictionary entries as dict_items([('a', 1),


items() dict1 = {'a': 1, 'b': 2} [Link]()
key-value tuple pairs. ('b', 2)])

Provides a view containing all the dict1 = {'a': 1, 'b': 2, 'c': 3}


keys() dict_keys(['a', 'b', 'c'])
keys in the dictionary. print([Link]())

dict1 = {'a': 1, 'b': 2, 'c': 3}


Removes a key-value pair by key
pop() print([Link]('b')) 2 and {'a': 1, 'c': 3}
and returns its value.
print(dict1)

dict1 = {'a': 1, 'b': 2, 'c': 3}


Removes and returns the most ('c', 3) and
popitem() print([Link]())
recently added key-value pair. {'a': 1, 'b': 2}
print(dict1)

Returns the value of a key; if dict1 = {'a': 1, 'b': 2}


2, 5, and
setdefault() missing, inserts it with a print([Link]('b', 5))
{'a': 1, 'b': 2, 'c': 5}
specified default. print([Link]('c', 5))

Merges another dictionary or dict1 = {'a': 1, 'b': 2}


iterable into the existing dict2 = {'b': 3, 'c': 4}
update() {'a': 1, 'b': 3, 'c': 4}
dictionary, updating keys if they [Link](dict2)
exist. print(dict1)

Returns a view object containing dict1 = {'x': 10, 'y': 20, 'z': 30} dict_values([10, 20,
values()
all dictionary values. print([Link]()) 30])

[Link]
STRING METHODS
Method Description Code Example Output

Converts the first letter of the str1 = "intensity coding" Intensity


capitalize()
string to uppercase. print([Link]()) coding

Converts the string to lowercase


casefold() str1 = "PYTHON" print([Link]()) python
for case-insensitive comparisons.

Aligns the string at the center with str1 = "AI"


center() **AI**
specified width. print([Link](6, '*'))

Counts occurrences of a substring str1 = "machine learning machine"


count() 2
in the string. print([Link]("machine"))

Returns the encoded version of the str1 = "AI"


encode() b'AI'
string. print([Link]())

Checks if the string ends with a str1 = "deep learning"


endswith() True
specific substring. print([Link]("learning"))

str1 = "A\tB\tC"
expandtabs() Sets the tab size within the string. A B C
print([Link](4))

Returns the index of the first str1 = "intensity coding"


find() 10
occurrence of a substring. print([Link]("coding"))

Formats specified values in the python str1 = "Hello, {}!".format("AI")


format() Hello, AI!
string. print(str1)

info = {'name': 'AI'}


Similar to format(), but uses a
format_map() str1 = "Hello,{name}!".format_map(info) Hello, AI!
mapping object.
print(str1)

Returns index of substring; raises str1 = "machine"


index() 4
error if not found. print([Link]("ine"))

Checks if all characters are str1 = "AI2025"


isalnum() True
alphanumeric. print([Link]())

Checks if all characters are str1 = "AI"


isalpha() True
alphabetic. print([Link]())

Returns True if all characters are str1 = "AI"


isascii() True
ASCII. print([Link]())

[Link]
STRING METHODS
Method Description Code Example Output

Checks if all characters are str1 = "123"


isdecimal() True
decimal digits. print([Link]())

Checks if all characters are str1 = "12345"


isdigit() True
digits. print([Link]())

Validates if string is a valid str1 = "variable_name"


isidentifier() True
Python identifier. print([Link]())

Checks if all letters are str1 = "intensity"


islower() True
lowercase. print([Link]())

Checks if all characters str1 = "2025"


isnumeric() True
represent numeric values. print([Link]())

Returns True if all characters are str1 = "AI ML"


isprintable() True
printable. print([Link]())

Checks if the string contains only str1 = " "


isspace() True
whitespace. print([Link]())

Checks if the string follows title str1 = "Machine Learning"


istitle() True
case. print([Link]())

Checks if all letters are str1 = "AI"


isupper() True
uppercase. print([Link]())

Joins iterable elements using the str1 = "-"


join() AI-ML-DL
string as separator. print([Link](['AI', 'ML', 'DL']))

Left-aligns the string in specified str1 = "AI"


ljust() AI****
width. print([Link](6, '*'))

str1 = "INTENSITY"
lower() Converts all letters to lowercase. intensity
print([Link]())

str1 = " AI" <br>


lstrip() Removes leading whitespace. 'AI'
print([Link]())

trans = [Link]('A', 'I')


Generates a translation table for
maketrans() str1 = "AI" II
replacement.
print([Link](trans))

[Link]
STRING METHODS
Method Description Code Example Output

Splits string into 3 parts using a str1 = "AI-ML-DL"


partition() ('AI', '-', 'ML-DL')
separator. print([Link]('-'))

Replaces occurrences of a str1 = "AI ML AI"


replace() DL ML DL
substring. print([Link]("AI", "DL"))

Finds last occurrence of str1 = "AI ML AI"


rfind() 6
substring. print([Link]("AI"))

Returns last index of substring; str1 = "AI ML AI"


rindex() 6
raises error if not found. print([Link]("AI"))

Right-aligns the string within str1 = "AI"


rjust() ****AI
specified width. print([Link](6, '*'))

Splits string into 3 parts, str1 = "AI-ML-DL"


rpartition() ('AI-ML', '-', 'DL')
searching from end. print([Link]('-'))

Splits string from the right using str1 = "AI,ML,DL"


rsplit() ['AI,ML', 'DL']
a separator. print([Link](' , ', 1))

str1 = "AI "


rstrip() Removes trailing whitespace. 'AI'
print([Link]())

Splits string into a list based on str1 = "AI ML DL"


split() ['AI', 'ML', 'DL']
separator. print([Link]())

str1 = "AI\nML\nDL"
splitlines() Splits string at line breaks. ['AI', 'ML', 'DL']
print([Link]())

Checks if string starts with a str1 = "AI ML"


startswith() True
specific substring. print([Link]("AI"))

Removes leading and trailing str1 = " AI ML "


strip() 'AI ML'
whitespace. print([Link]())

Swaps lowercase to uppercase str1 = "Ai Ml"


swapcase() aI mL
and vice versa. print([Link]())

Converts first letter of each word str1 = "intensity coding"


title() Intensity Coding
to uppercase. print([Link]())

[Link]
STRING METHODS
Method Description Code Example Output

trans = [Link]({'A': '@', 'I': '1'})


Modifies string using a
translate() str1 = "AI" @1
translation table.
print([Link](trans))

str1 = "ai ml"


upper() Converts string to uppercase. AI ML
print([Link]())

Pads string with leading zeros to str1 = "42"


zfill() 00042
reach desired width. print([Link](5))

TUPLE METHODS
Method Description Code Example Output

Returns the number of times a specified number_tup = (1, 2, 2, 3, 2)


count() 3
value appears in a tuple. print(number_tup.count(2))

Searches for a specified value and number_tup = (10, 20, 30, 20)
index() 2
returns its position (index). print(number_tup.index(30))

[Link]
PYTHON BUILT-IN FUNCTIONS
Function Description Code Example Output

Returns the absolute (non-negative)


abs() print(abs(-10)) 10
value of a number.

Returns True if all elements in an


all() print(all([1, True, 5])) True
iterable are true.

Returns True if at least one element


any() print(any([0, False, 3])) True
in an iterable is true.

Converts object to a string,


ascii() print(ascii("Intensity©")) 'Intensity\\u00a9'
escaping non-ASCII chars.

Converts an integer to a binary


bin() print(bin(10)) '0b1010'
string.

Converts a value to a Boolean (True


bool() print(bool(0)) False
or False).

b = bytearray([65, 66,
bytearray() Creates a mutable array of bytes. bytearray(b'ABC')
67])print(b)

bytes() Creates an immutable bytes object. print(bytes("Hi", "utf-8")) b'Hi'

Checks if an object can be called


callable() print(callable(print)) True
like a function.

Returns the character for a Unicode


chr() print(chr(65)) A
code point.

class Demo:
@classmethod
Converts a method into a class
classmethod() def show(cls): Class Method
method.
print("Class Method")
[Link]()

Compiles code string into a code code = compile('3+5', '', 'eval')


compile() 8
object. print(eval(code))

complex() Creates a complex number. print(complex(2, 3)) (2+3j)

[Link]
PYTHON BUILT-IN FUNCTIONS
Function Description Code Example Output

class A:
Deletes an attribute from an x=10
delattr() False
object. delattr(A,'x')
print(hasattr(A,'x'))

dict() Creates a dictionary object. print(dict(a=1,b=2)) {'a':1,'b':2}

['__add__',
Lists attributes and
dir() print(dir([ ])[:3]) '__class__',
methods of an object.
'__contains__']

Returns quotient and


divmod() print(divmod(10,3)) (3,1)
remainder as tuple.

Adds index numbers to for i,v in enumerate(['a','b']):


enumerate() 0 a1 b
iterable elements. print(i,v)

Evaluates a string as Python


eval() print(eval('5*3')) 15
expression.

Executes Python code


exec() exec('x=5;print(x)') 5
dynamically.

nums=[1,2,3,4]
Filters elements using a
filter() even=list(filter(lambda x:x%2==0,nums)) [2,4]
condition.
print(even)

float() Converts a value to a float. print(float(5)) 5.0

Formats a value according


format() print(format(3.14159,'.2f')) 3.14
to a format specifier.

s=frozenset([1,2,3])
frozenset() Creates an immutable set. frozenset({1,2,3})
print(s)

class A:
Retrieves the value of an
getattr() x=42 42
object’s attribute.
print(getattr(A,'x'))

['__name__',
Returns the global symbol
globals() print(list(globals().keys())[:3]) '__doc__',
table as a dictionary.
'__package__']

[Link]
PYTHON BUILT-IN FUNCTIONS
Function Description Code Example Output

class A:
Checks if an object has a specific
hasattr() x=10 True
attribute.
print(hasattr(A,'x'))

hash() Returns the hash value of an object. print(hash('intensity')) (varies)

Displays documentation for a (Opens help


help() help(len)
module, class, or function. text)

Converts an integer to hexadecimal


hex() print(hex(255)) '0xff'
format.

x=10; (unique
id() Returns the unique ID of an object.
print(id(x)) integer)

input() Reads a line of input from the user. input("Enter name: ") (User input)

int() Converts a value to an integer. print(int(5.9)) 5

Checks if an object is an instance


isinstance() print(isinstance(5,int)) True
of a class/type.

class A:
pass
Checks if a class is a subclass of
issubclass() class B(A): True
another class.
pass
print(issubclass(B,A))

it=iter([1,2])
iter() Converts an iterable into an iterator. 1
print(next(it))

Returns the number of items in an


len() print(len([1,2,3])) 3
object.

list() Creates a list from an iterable. print(list('AI')) ['A','I']

def test():
Returns the current local symbol x=5
locals() {'x':5}
table. print(locals())
test()

Applies a function to all items in an nums=[1,2,3]


map() [2,4,6]
iterable. print(list(map(lambda x:x*2,nums)))

[Link]
PYTHON BUILT-IN FUNCTIONS
Function Description Code Example Output

max() Returns the largest item in an iterable. print(max([1,5,3])) 5

Returns a memory view object of a v=memoryview(b'abc')


memoryview() 97
bytes-like object. print(v[0])

min() Returns the smallest item in an iterable. print(min([1,5,3])) 1

it=iter([10,20])
next() Returns the next item from an iterator. 10
print(next(it))

o=object(); <class
object() Returns a new featureless object.
print(type(o)) 'object'>

Converts an integer to octal string


oct() print(oct(8)) '0o10'
format.

f=open('[Link]','w')
open() Opens a file and returns a file object. [Link]('Hi') (Creates file)
[Link]()

Converts a character to its Unicode


ord() print(ord('A')) 65
code point.

pow() Computes power (xʸ). print(pow(2,3)) 8

Intensity
print() Outputs text to the console. print("Intensity Coding")
Coding

class A:
def __init__(self):
self._x=5
property() Returns a property object for a class. 5
x=property(lambda
self:self._x)
print(A().x)

range() Generates a sequence of numbers. print(list(range(3))) [0,1,2]

Returns a string that represents an


repr() print(repr('AI')) "'AI'"
object.

Returns an iterator that accesses


reversed() print(list(reversed([1,2,3]))) [3,2,1]
sequence in reverse.

[Link]
PYTHON BUILT-IN FUNCTIONS
Function Description Code Example Output

round() Rounds a number to given decimals. print(round(3.1415,2)) 3.14

set() Creates a new set object. print(set([1,2,2,3])) {1,2,3}

class A:
pass
setattr() Sets an attribute on an object. a=A(); 100
setattr(a,'x',100)
print(a.x)

s='Python';
slice() Creates a slice object for slicing sequences. 'Pyt'
print(s[slice(0,3)])

sorted() Returns a sorted list from an iterable. print(sorted([3,1,2])) [1,2,3]

class A:
@staticmethod
Defines a static method (no access to
staticmethod() def show(): Static
class/instance).
print('Static')
[Link]()

str() Converts a value to string. print(str(123)) '123'

sum() Returns the sum of iterable elements. print(sum([1,2,3])) 6

class A:
def show(self):
print('A')
super() Returns proxy object for parent class. class B(A): A
def show(self):
super().show()
B().show()

tuple() Creates a tuple from an iterable. print(tuple([1,2])) (1,2)

type() Returns type/class of object. print(type(10)) <class 'int'>

class A:
{'__module__'
vars() Returns __dict__ of an object. x=1
:..., 'x':1, ...}
print(vars(A))

zip() Combines iterables into tuples. print(list(zip([1,2],[3,4]))) [(1,3),(2,4)]

[Link]
Found this helpful ?

Follow on LinkedIn
Master AI/ML with Intensity Coding

@bhavdippatel2020

Like Comment Share Save

Each Lesson At Intensity Coding


Includes Everything You Need

THEORY MADE SIMPLE PYTHON CODE


Complex ideas explained Hands-on coding for
in an easy way practice

VISUAL LEARNING MATH BEHIND AI/ML


Visual diagrams for Step-by-step explanation
clarity of core concepts

[Link]

You might also like