PYTHON
Python Built In Method
Python
Python Built In Method
No Function Description
Returns the non-negative value of a number, regardless of its
1 abs()
sign.
2 all() Returns True if every item in an iterable is true.
3 any() Returns True if at least one item in an iterable is true.
Converts an object to a string, replacing non-ASCII characters
4 ascii()
with escape sequences.
5 bin() Converts a number to its binary representation.
6 bool() Returns the boolean representation of a given object.
7 bytearray() Creates an array of bytes from a sequence.
8 bytes() Creates an immutable bytes object.
9 callable() Checks if an object can be called like a function or method.
10 chr() Converts a Unicode code point to its corresponding character.
11 classmethod() Turns a method into a class method.
12 compile() Compiles a source code string into a code object for execution.
No Function Description
13 complex() Creates a complex number from real and imaginary parts.
14 delattr() Removes a specified attribute from an object.
15 dict() Creates a dictionary from key-value pairs.
16 dir() Lists all attributes and methods of an object.
Returns both the quotient and remainder when dividing two
17 divmod()
numbers.
Converts a collection into an enumerated object with index-value
18 enumerate()
pairs.
19 eval() Evaluates a string expression and returns the result.
20 exec() Executes a given string or object as Python code.
21 filter() Filters items in an iterable based on a function’s criteria.
22 float() Converts a number or string to a floating-point number.
23 format() Formats a value into a specified string format.
24 frozenset() Creates an immutable set from elements.
25 getattr() Retrieves the value of a specified attribute from an object.
26 globals() Returns the global symbol table as a dictionary.
27 hasattr() Checks if an object has a specific attribute or method.
28 hash() Returns the hash value of an object, useful for hash tables.
29 help() Launches the interactive help system for Python.
30 hex() Converts a number to its hexadecimal string representation.
31 id() Returns the unique identifier of an object.
32 input() Allows the user to input data from the keyboard.
33 int() Converts a value to an integer.
34 isinstance() Checks if an object is an instance of a specific class or type.
35 issubclass() Checks if a class is a subclass of another class.
36 iter() Converts an iterable into an iterator.
No Function Description
37 len() Returns the number of items in an object.
38 list() Creates a list from an iterable.
39 locals() Returns the local symbol table as an updated dictionary.
40 map() Applies a function to all items in an iterable and returns the result.
41 max() Returns the largest item in an iterable.
Creates a memory view object that allows direct access to the
42 memoryview()
internal data of a byte-based object without copying it.
43 min() Returns the smallest item in an iterable.
44 next() Returns the next item in an iterator.
45 object() Creates a new object (base class).
46 oct() Converts a number to its octal string representation.
47 open() Opens a file and returns a file object for reading or writing.
48 ord() Converts a character to its corresponding Unicode code point.
49 pow() Computes x raised to the power of y.
50 print() Outputs text or data to the console.
51 property() Creates, gets, sets, or deletes an object's property.
52 range() Generates a sequence of numbers, starting from 0 by default.
Returns a string representation of an object, suitable for
53 repr()
debugging.
54 reversed() Returns an iterator that yields items in reverse order.
55 round() Rounds a number to a specified number of decimal places.
56 set() Creates a new set object from an iterable.
57 setattr() Sets a value for a specified attribute on an object.
58 slice() Creates a slice object for extracting portions of iterables.
59 sorted() Returns a sorted list from an iterable.
60 staticmethod() Converts a method into a static method, bound to the class.
No Function Description
61 str() Converts an object to its string representation.
62 sum() Sums the elements of an iterable.
63 super() Returns a proxy object representing the parent class.
64 tuple() Creates a tuple from an iterable.
65 type() Returns the type or class of an object.
Returns an object's __dict__ attribute, showing its internal
66 vars()
variables.
67 zip() Combines multiple iterables into a single iterator of tuples.
1. abs()
Point Description
The abs() function returns the absolute (non-negative) value of a number.
Use Case
For complex numbers, it returns the magnitude.
Syntax abs(n)
n (Required) — A numeric value (integer, float, or complex number) for
Parameter
which the absolute value is to be calculated.
Useful Information
No. Point Description
Works with Different Number Accepts integers, floats, and complex
1
Types numbers.
2 Returns Non-Negative Value Always returns a positive value or zero.
Returns the magnitude: abs(a + bj) = √(a² +
3 For Complex Numbers
b²).
# Example 1: Absolute value of a complex number
x = abs(1 + 2j)
print(x)
# Output: 2.23606797749979
# Explanation: sqrt(1**2 + 2**2) = sqrt(1 + 4) = sqrt(5)
# Example 2: Absolute value of a negative float
x = abs(-2.50)
print(x)
# Output: 2.5
# Explanation: Converts negative number to positive
2.23606797749979
2.5
2. all()
Point Description
The all() function checks whether every element in an iterable evaluates
Use Case to True. It is often used to validate data integrity or check uniform
conditions across datasets.
Syntax all(iterable)
iterable (Required) — Any iterable (e.g., list, tuple, set, or dictionary)
Parameter
whose elements are to be evaluated as Boolean values.
Useful Information
No. Point Description
Returns True only if all items are truthy (non-zero,
1 Evaluates Truthiness
non-empty, etc.).
Returns True for Empty If the iterable is empty, the function returns True by
2
Iterables default.
Works Across Iterable
3 Compatible with lists, tuples, sets, and dictionaries.
Types
No. Point Description
Evaluates Dictionary Keys When applied to a dictionary, it evaluates keys—not
4
Only values.
# Example 1: Check if all feature values are normalized (between 0 and 1)
features = [0.8, 0.5, 0.95, 1.0]
are_all_normalized = all(0 <= x <= 1 for x in features)
print(are_all_normalized)
# Output: True
# Explanation: All values fall within the 0-1 normalization range
# Example 2: Check if all model predictions are greater than a threshold
predictions = {0.92, 0.87, 0.89, 0.95}
threshold = 0.85
is_confident = all(p > threshold for p in predictions)
print(is_confident)
# Output: True
# Explanation: Every prediction exceeds the confidence threshold
# Example 3: Check for missing values in dataset (0 represents missing)
data_row = [1, 1, 0, True]
is_valid_row = all(data_row)
print(is_valid_row)
# Output: False
# Explanation: The row contains a missing or invalid (0) value
# Example 4: Dictionary with feature presence (keys)
features_present = {1: "age", 2: "income", 0: "education"}
check_all_present = all(features_present)
print(check_all_present)
# Output: False
# Explanation: Key '0' evaluates to False, so not all features are
present
# Example 5: Empty input vector
empty_vector = ()
check_empty = all(empty_vector)
print(check_empty)
# Output: True
# Explanation: By definition, all() returns True for empty iterables
True
True
False
False
True
3. any()
Point Description
The any() function checks whether at least one element in an iterable is
Use Case True. It returns True as soon as it finds the first truthy value; otherwise, it
returns False.
Syntax any(iterable)
iterable (Required) — An iterable like a list, tuple, set, or dictionary
Parameter
containing elements to evaluate.
Useful Information
No. Point Description
Returns on First True Stops checking once a single True or truthy value is
1
Value found.
Returns False for Empty
2 If the iterable is empty, any() returns False.
Iterables
Accepts Multiple Iterable
3 Works with lists, tuples, sets, and dictionaries.
Types
Checks Dictionary Keys When applied to a dictionary, it evaluates the
4
Only truthiness of keys—not values.
# Example 1: Check if any input features are missing (0 indicates
missing)
input_vector = [1, 0, 1, 1]
has_missing = any(x == 0 for x in input_vector)
print(has_missing)
# Output: True
# Explanation: At least one feature is marked as missing (0)
# Example 2: Identify if any prediction scores fall below a safe
threshold
model_outputs = [0.92, 0.88, 0.76, 0.95]
threshold = 0.80
any_low_confidence = any(score < threshold for score in model_outputs)
print(any_low_confidence)
# Output: True
# Explanation: One of the predictions is below the defined threshold
# Example 3: Dictionary with encoded feature flags (keys)
feature_flags = {0: "inactive", 1: "active"}
any_active_flag = any(feature_flags)
print(any_active_flag)
# Output: True
# Explanation: Key '1' is truthy, so `any()` returns True
# Example 4: Check if any model evaluation metric is perfect
metrics = (0.9, 1.0, 0.85)
has_perfect_score = any(m == 1.0 for m in metrics)
print(has_perfect_score)
# Output: True
# Explanation: A perfect score (1.0) exists in the tuple
# Example 5: Empty input check
empty_input = {}
x = any(empty_input)
print(x)
# Output: False
# Explanation: No elements to evaluate, so returns False
True
True
True
True
False
4. ascii()
Point Description
The ascii() function returns a string representation of an object, where
Use Case non-ASCII characters are escaped using Unicode code points. It ensures
the result is readable in ASCII-only environments.
Syntax ascii(object)
object (Required) — Any object such as a string, list, tuple, or dictionary
Parameter
that needs to be represented in ASCII form.
Useful Information
No. Point Description
Converts to ASCII-Safe Escapes non-ASCII characters like å into \u00e5 or
1
Format similar.
Supports Various Data
2 Accepts strings, lists, dictionaries, tuples, etc.
Types
Output is Always a
3 Returns a string with all non-ASCII characters escaped.
String
Useful in Logging and Especially helpful when saving or logging data in
4
Serialization environments that only support ASCII characters.
Doesn’t Modify the Returns a new ASCII-safe string representation, leaving
5
Original Object the original untouched.
# Example : String containing non-ASCII characters
text = "Model trained by Ståle on dataset µData"
ascii_output = ascii(text)
print(ascii_output)
# Output: 'Model trained by St\xe5le on dataset \xb5Data'
# Explanation: Non-ASCII characters like 'å' and 'µ' are escaped in
ASCII-safe form
'Model trained by St\xe5le on dataset \xb5Data'
5. bin()
Point Description
The bin() function converts a given integer into its binary string
Use Case
representation, prefixed with 0b.
Syntax bin(number)
Parameter number (Required) — Any integer value you want to convert to binary.
Useful Information
No. Point Description
Returns a Binary Output is a string showing the binary equivalent of the
1
String integer.
Always Prefixed with
2 The result starts with 0b, indicating a binary value.
0b
Only Works with
3 Passing a non-integer will raise a TypeError.
Integers
Useful in Bitwise Commonly used in scenarios involving low-level bit
4
Operations manipulation.
The binary value is returned as a new string object; the
5 Output is Immutable
original integer remains unchanged.
num = 36
binary_value = bin(num)
print(binary_value)
# Output: '0b100100'
# Explanation: The integer 36 is represented as '100100' in binary,
# and the '0b' prefix signifies that it's a binary number.
0b100100
6. bool()
Point Description
The bool() function is used to evaluate a value and return either True or
Use Case
False based on its truthiness.
Syntax bool(object)
object (Optional) — Any value such as string, number, list, or other object
Parameter
types. If no argument is given, it returns False.
Useful Information
No. Point Description
1 Evaluates Truthiness Returns True for most non-empty or non-zero objects.
Returns False For Empty sequences ([], (), {}), 0, None, and False itself
2
Certain Values evaluate to False.
Converts to Boolean
3 Useful for conditional checks or logical operations.
Type
Works with Any Object Can be used with numbers, strings, lists, dictionaries,
4
Type and even custom objects.
No Argument Returns
5 Calling bool() with no arguments gives False.
False
# Example 1: Non-zero integer
x = bool(1)
print(x)
# Output: True
# Example 2: Empty list
x = bool([])
print(x)
# Output: False
# Example 3: None value
x = bool(None)
print(x)
# Output: False
True
False
False
7. bytearray()
Point Description
The bytearray() function returns a mutable sequence of bytes, similar to
Use Case a list of integers ranging from 0 to 255. It’s commonly used for binary data
manipulation.
Syntax bytearray(source, encoding, errors)
source (Optional) — The data to convert into a bytearray (e.g., integer,
Parameter
string, list, or bytes).
encoding (Optional) — Specifies the encoding if the source is a string.
errors (Optional) — Defines how to handle encoding errors (e.g., 'strict',
'ignore').
Useful Information
No. Point Description
Mutable Alternative to Unlike bytes(), bytearray() allows modifying its
1
bytes contents.
Converts Strings, Lists, and Can convert strings (with encoding), lists of integers,
2
More or other byte-like objects.
No. Point Description
If an integer is passed, creates a zero-initialized
3 Initializes Empty Buffer
bytearray of that length.
Supports Encoding and
4 Useful when dealing with string-to-byte conversions.
Error Handling
Commonly used in file and network data
5 Works Well for Binary I/O
manipulation.
# Example 1: Create a bytearray of length 4 (all bytes initialized to
zero)
x = bytearray(4)
print(x)
# Output: bytearray(b'\x00\x00\x00\x00')
# Explanation: Returns a bytearray of 4 bytes, each initialized to zero.
# Example 2: Create a bytearray from a string using UTF-8 encoding
text = "intensity"
x = bytearray(text, "utf-8")
print(x)
# Output: bytearray(b'intensity')
# Explanation: Each character in the string is converted to its UTF-8
byte representation.
# Example 3: Modify a byte in the bytearray
x[0] = 73 # Replace 'i' (ASCII 105) with 'I' (ASCII 73)
print(x)
# Output: bytearray(b'Intensity')
bytearray(b'\x00\x00\x00\x00')
bytearray(b'intensity')
bytearray(b'Intensity')
8. bytes()
Point Description
The bytes() function returns an immutable sequence of bytes. It’s used
Use Case for handling binary data or converting data types (like strings or lists) into a
bytes object.
Syntax bytes(source, encoding, errors)
source (Optional) — The input to convert into a bytes object (can be an
Parameter
integer, string, list, etc.).
encoding (Optional) — The encoding to use if the source is a string.
errors (Optional) — Specifies how to handle encoding errors ('strict',
'ignore', etc.).
Useful Information
No. Point Description
Immutable Byte Unlike bytearray(), the resulting object cannot be
1
Sequence altered after creation.
Accepts Multiple Data Works with integers, strings, lists of integers (0–255), or
2
Types other byte-like objects.
Passing an integer creates a bytes object of that length
3 Zero-Initialized Buffer
with all bytes set to 0.
Requires Encoding for If a string is passed, encoding must be specified to
4
Strings convert it into bytes.
Common in Binary Often used for reading/writing files, socket
5
Operations communication, and serialization.
# Example 1: Create an empty bytes object of size 4
x = bytes(4)
print(x)
# Output: b'\x00\x00\x00\x00'
# Explanation: Generates 4 bytes initialized to zero (immutable).
# Example 2: Convert a string to bytes using UTF-8 encoding
text = "intensity"
x = bytes(text, "utf-8")
print(x)
# Output: b'intensity'
# Example 3: Convert a list of integers to a bytes object
x = bytes([73, 110, 116])
print(x)
# Output: b'Int'
# Explanation: The integers represent ASCII values of characters.
b'\x00\x00\x00\x00'
b'intensity'
b'Int'
9. callable()
Point Description
The callable() function checks whether the given object can be called
Use Case like a function, meaning it can be invoked using parentheses (). It returns
True if the object is callable, otherwise False.
Syntax callable(object)
object (Required) — Any Python object you want to test for callability (e.g.,
Parameter
functions, classes, or objects with a __call__() method).
Useful Information
No. Point Description
Always returns either True (if callable) or False (if
1 Returns a Boolean
not).
2 Functions are Callable User-defined and built-in functions return True.
Integers, Strings, Lists are
3 Regular data types like int, str, list return False.
Not Callable
Classes and Objects Can If a class implements the __call__() method, its
4
Be Callable instances are callable.
No. Point Description
Useful when designing APIs or decorators that
5 Helpful for Type-Checking
accept functions or callable objects.
# Example 1: Check if a user-defined function is callable
def example_function():
return "This is callable!"
print(callable(example_function))
# Output: True
# Explanation: Functions can be called, so this returns True.
# Example 2: Check if an integer is callable
number = 10
print(callable(number))
# Output: False
# Explanation: Integers are not callable objects.
# Example 3: Check if a class instance is callable (with __call__)
class CallableObject:
def __call__(self):
print("I can be called like a function.")
obj = CallableObject()
print(callable(obj))
# Output: True
# Explanation: The object defines __call__, so it's callable.
True
False
True
10. chr()
Point Description
Use Case The chr() function is used to return the character that corresponds to a
specified Unicode code point (integer). It's the inverse of the ord()
Point Description
function.
Syntax chr(number)
number (Required) — An integer value that represents a valid Unicode code
Parameter
point
Useful Information
No. Point Description
Converts Code to Translates a Unicode integer value into its character
1
Character equivalent.
Only accepts integers in the valid Unicode range (0 to
2 Unicode Range
0x110000).
Use chr() to get a character from a code point, and
3 Complement of ord()
ord() to go the other way.
Useful in Encoding Commonly used in tasks like encoding, compression, or
4
Tasks handling ASCII tables.
If the number is outside the allowed range, a ValueError
5 Raises ValueError
is raised.
# Example 1: Convert Unicode code point 97 to character
char = chr(97)
print(char)
# Output: a
# Explanation: Unicode 97 corresponds to the lowercase letter 'a'.
# Example 2: Convert multiple Unicode points
print(chr(65)) # Output: A
print(chr(8364)) # Output: €
print(chr(128512)) # Output: 😀
# Example 3: Invalid Unicode code point (out of range)
try:
print(chr(1114112)) # Just beyond the Unicode limit
except ValueError as e:
print("Error:", e)
# Output: Error: chr() arg not in range(0x110000)
a
A
€
😀
Error: chr() arg not in range(0x110000)
11. classmethod()
Point Description
The classmethod() function is used to convert a method into a class
method, which can be called on the class itself or on instances of the class.
Use Case
It receives the class (cls) as its first argument instead of the instance
(self).
Syntax classmethod(function)
Parameter function (Required) — A method that should behave as a class method.
Useful Information
No. Point Description
Works with Class, Not Receives the class (cls) as the first parameter,
1
Instance allowing access to class-level data.
Shared Across All Useful when a method needs to work with or modify
2
Instances class-level attributes, not instance data.
classmethod() is usually used in the form of a
Typically Used with
3 decorator @classmethod above the method
@classmethod Decorator
definition.
Can Create Alternative Often used to define factory methods that construct
4
Constructors objects in different ways.
Not the Same as Unlike staticmethod(), class methods still receive
5
staticmethod() the class context (cls) as an argument.
class IntensityLogger:
log_entries = [] # Class-level attribute shared across all instances
def __init__(self, message):
[Link] = message
@classmethod
def log(cls, message):
cls.log_entries.append(message) # Accesses class attribute
print(f"[CLASS LOG] {message}")
# Calling the class method using the class
[Link]("Tutorial started.")
# Output: [CLASS LOG] Tutorial started.
# Accessing the shared log across instances
print(IntensityLogger.log_entries)
# Output: ['Tutorial started.']
[CLASS LOG] Tutorial started.
['Tutorial started.']
### Creating a Class Method Without a Decorator
class IntensityCounter:
count = 0
def increase(cls):
[Link] += 1
print("Increased:", [Link])
# Convert the regular method into a class method
[Link] = classmethod([Link])
# Call it
[Link]()
# Output: Increased: 1
Increased: 1
12. compile()
Point Description
The compile() function transforms a string, bytes, or AST (Abstract
Syntax Tree) object into a Python code object, which can then be executed
Use Case
using exec() or eval(). This is useful when dynamically executing Python
code at runtime.
compile(source, filename, mode, flags=0, dont_inherit=False,
Syntax
optimize=-1)
source (Required) — The actual code to compile (string, bytes, or AST
Parameters
object).
filename (Required) — A filename string (can be dummy if not from a file).
mode (Required) — Must be 'exec', 'eval', or 'single'.
flags (Optional) — Compilation flags. Default is 0.
dont_inherit (Optional) — Prevents inheriting future statements. Default
is False.
optimize (Optional) — Sets the optimization level (-1, 0, 1, 2).
Useful Information
No. Point Description
Compiles to Converts source code to an internal code object that can
1
Executable Code be executed with exec() or eval().
Supports Three 'eval' for expressions, 'exec' for multiple statements,
2
Modes and 'single' for one-line statements.
Dynamic Code Ideal for scenarios where Python code needs to be
3
Execution created or modified at runtime.
No. Point Description
Filename is Arbitrary If source is not from a file, filename can be any string
4
for Strings (e.g., 'test').
Accepts AST objects from the ast module for advanced
5 Works With AST
usage like code transformation.
# Example 1: Using `compile()` with `eval` mode
# Compiles a single expression and evaluates it
x = compile('55 + 10', 'test', 'eval')
result = eval(x)
print(result)
# Output: 65
# Example 2: Using `compile()` with `exec` mode
# Compiles multiple statements and executes them
code_block = '''
print("Executing block...")
x = 5 * 3
print("Result:", x)
'''
compiled_code = compile(code_block, 'demo', 'exec')
exec(compiled_code)
# Output:
# Executing block...
# Result: 15
#Example 3: One-liner using `exec`
x = compile('print(60)', 'script', 'exec')
exec(x)
# Output: 60
65
Executing block...
Result: 15
60
13. complex()
Point Description
The complex() function creates a complex number by specifying the real
Use Case and imaginary components. It can also interpret a string representation of
a complex number.
Syntax complex(real, imaginary)
real (Required) — The real part of the complex number. Can be an integer,
Parameters
float, or string like '3+5j'. Defaults to 0 if not provided.
imaginary (Optional) — The imaginary part of the complex number. Only
used if real is not a string. Defaults to 0.
Useful Information
No. Point Description
Supports Two Input Accepts numbers or a single string representing a
1
Types complex number.
Returns a Complex The result will be in the format a + bj where a is the
2
Object real part and b is the imaginary part.
Imaginary Suffix Must Be In Python, imaginary numbers are written using j, not
3
j i (e.g., 3+5j).
Input String Ignores When the first argument is a string, the second
4
Second Parameter parameter must be omitted.
#Example 1: Using two numeric values
# Create a complex number with real part 3 and imaginary part 5
x = complex(1, 2)
print(x)
# Output: (1+2j)
# Example 2: Using a string representation
# Create a complex number from a string
x = complex('1+2j')
print(x)
# Output: (1+2j)
#Example 3: Omitting the imaginary part
# Only real part provided, imaginary defaults to 0
x = complex(4)
print(x)
# Output: (4+0j)
(1+2j)
(1+2j)
(4+0j)
14. delattr()
Point Description
The delattr() function removes a specified attribute from an object or
Use Case
class by referencing the attribute name as a string.
Syntax delattr(object, attribute)
Parameter object (Required) — The target object or class instance.
attribute (Required) — A string representing the name of the attribute to
be deleted.
Useful Information
No. Point Description
Deletes Class or Instance Can remove attributes from both class definitions
1
Attributes and instantiated objects.
Requires Attribute Name
2 Accepts the attribute name dynamically as a string.
as String
3 Raises AttributeError If the specified attribute does not exist.
Often Used in Meta- Useful when managing dynamic or configurable
4
programming object states.
Cannot Delete Special Should not be used to remove Python’s built-in
5
Attributes special methods like __init__, __dict__, etc.
Example 1: Removing an Attribute from a Class
# Define a class with multiple attributes
class Person:
name = "Alice"
age = 30
country = "Canada"
# Delete the 'age' attribute from the class
delattr(Person, 'age')
# Check if the attribute still exists
print(hasattr(Person, 'age'))
# Output: False
# Explanation: The 'age' attribute has been removed from the class
False
Example 2: Removing an Attribute from an Object
Instance
# Define a class and initialize attributes
class User:
def __init__(self):
[Link] = "intensity_writer"
[Link] = "ML Author"
# Create an object of the User class
u = User()
# Remove the 'role' attribute from the object
delattr(u, 'role')
# Verify that the attribute is removed
print(hasattr(u, 'role'))
# Output: False
# Explanation: 'role' no longer exists in the object instance
False
15. dict()
Point Description
The dict() function is used to create a new dictionary, which is an
Use Case
unordered and mutable collection of key-value pairs.
Syntax dict(**kwargs)
**kwargs (Optional) — Any number of keyword arguments in the form
Parameter
key=value, which become the dictionary’s keys and values.
Useful Information
No. Point Description
Returns a Dictionary Creates a dictionary from keyword arguments or other
1
Object mappings.
Supports Various Data Can be initialized from lists of tuples, keyword
2
Formats arguments, or other dictionary-like objects.
Keys must be of an immutable type such as strings,
3 Keys Must Be Hashable
numbers, or tuples.
More Than Just Keyword Also accepts iterable key-value pairs via
4
Args dict([(key1, val1), (key2, val2)]).
Frequently Used in Data Ideal for configurations, structured data, or ML
5
Manipulation parameters.
# Example 1: Creating a Dictionary with Keyword Arguments
# Creating a dictionary using keyword arguments
person_info = dict(name="Raj", age=40, country="India")
print(person_info)
# Output: {'name': 'Raj', 'age': 40, 'country': 'India'}
{'name': 'Raj', 'age': 40, 'country': 'India'}
# Example 2: Using `dict()` with a List of Tuples
# Creating a dictionary from a list of tuples
params = dict([("learning_rate", 0.01), ("batch_size", 32)])
print(params)
# Output: {'learning_rate': 0.01, 'batch_size': 32}
{'learning_rate': 0.01, 'batch_size': 32}
16. dir()
Point Description
The dir() function lists all the valid attributes (properties and methods) of
Use Case a specified object. This includes custom attributes as well as built-in
Python attributes.
Syntax dir(object)
object (Optional) — The object whose attributes you want to inspect. If no
Parameter
object is provided, it returns the names in the current local scope.
Useful Information
No. Point Description
Helps with Useful to explore available methods and attributes of
1
Introspection objects, modules, and classes.
Shows Built-in Returns not just user-defined, but also special and
2
Attributes inherited attributes.
Works Without If no argument is passed, it returns the names in the
3
Parameters current scope.
4 Returns a List Always returns a list of attribute names as strings.
Commonly Used in Helps developers understand object capabilities during
5
Debugging runtime.
# Define a simple class with some attributes
class ModelConfig:
model_name = "RandomForest"
n_estimators = 100
max_depth = 10
# Use dir() to inspect available attributes and methods
print(dir(ModelConfig))
# Output (partial, varies by environment):
# ['__class__', '__delattr__', ..., 'max_depth', 'model_name',
'n_estimators']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__le__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '__weakref__', 'max_depth', 'model_name',
'n_estimators']
17. divmod()
Point Description
The divmod() function returns a tuple containing both the quotient and
Use Case
remainder from dividing one number (dividend) by another (divisor).
Syntax divmod(dividend, divisor)
Parameters dividend (Required) — The number to be divided.
divisor (Required) — The number by which to divide.
Useful Information
No. Point Description
1 Returns a Tuple The result is a tuple in the form (quotient, remainder).
Works with Integers
2 Supports both integer and floating-point operands.
and Floats
Faster and cleaner than calling a // b and a % b
3 Efficient Alternative
separately.
Often used in loop counters or position-based
4 Useful in Iteration
calculations.
If both inputs are integers, the result is integer-based; if
5 Type-Dependent
floats are used, so are float results.
# Use divmod to divide 9 by 4
result = divmod(9, 4)
# Display the result
print(result)
# Output:
# (2, 1)
(2, 1)
18. enumerate()
Point Description
The enumerate() function adds a counter to an iterable and returns it as
Use Case an enumerate object, which can be converted into a list or used directly in
loops.
Syntax enumerate(iterable, start=0)
Parameters iterable (Required) — Any iterable like a list, tuple, or string.
start (Optional) — The number to start counting from. Default is 0.
Useful Information
No. Point Description
Returns an Enumerate
1 Wraps the iterable with index-value pairs.
Object
2 Common in Loops Ideal for use in for loops to get both index and item.
3 Custom Starting Index You can define any starting point for the counter.
4 Works with Any Iterable Accepts strings, lists, tuples, etc.
Does not modify the original iterable and avoids
5 Lightweight and Efficient
manual indexing.
# Define a tuple
layers = ('Input 1', 'Input 2', 'Input 3', 'Input 4', 'Input 5')
# Use enumerate to index
indexed_layers = enumerate(layers)
# Convert to list and print the result
print(list(indexed_layers))
# Output:
# [(0, 'Input 1'), (1, 'Input 2'), (2, 'Input 3'), (3, 'Input 4'), (4,
'Input 5')]
[(0, 'Input 1'), (1, 'Input 2'), (2, 'Input 3'), (3, 'Input 4'), (4,
'Input 5')]
19. eval()
Point Description
The eval() function parses a string and executes it as a valid Python
Use Case expression. It’s often used to evaluate expressions dynamically during
runtime.
Syntax eval(expression, globals=None, locals=None)
Parameter expression (Required): A valid Python expression provided as a string.
globals (Optional): A dictionary of global variables accessible during
evaluation.
locals (Optional): A dictionary of local variables accessible during
evaluation.
Useful Information
No. Point Description
Must Be a Valid The input must be a valid Python expression, not a block
1
Expression of code.
Useful for Dynamic Especially helpful when you want to evaluate formulas or
2
Evaluation conditions at runtime.
Never use eval() on untrusted input as it can execute
3 Security Risk
arbitrary code.
Can Use Global & Evaluate expressions using specified global and local
4
Local Context variable scopes.
eval() returns the result of the evaluated expression,
5 Returns the Result
unlike exec() which returns nothing.
# Define a dictionary of hyperparameters
params = {
"learning_rate": 0.01,
"epochs": 10,
"batch_size": 32
}
# Expression to calculate total steps dynamically
expr = "(epochs * 5000) // batch_size"
# Use eval() with params as the local context
total_steps = eval(expr, {}, params)
print("Total training steps:", total_steps)
# Output:
# Total training steps: 1562
# Explanation:
# eval() computed the number of training steps based on given parameters.
Total training steps: 1562
20. exec()
Point Description
The exec() function dynamically executes Python code blocks provided as
Use Case strings or code objects. Unlike eval(), it supports full code blocks
including variable assignments, loops, and function definitions.
Syntax exec(object, globals=None, locals=None)
Parameter object (Required): A string or a compiled code object containing valid
globals (Optional): A dictionary representing the global context for
execution.
locals (Optional): A dictionary representing the local context for execution.
Useful Information
No. Point Description
Supports Full Code Can run multi-line statements, such as function
1
Blocks definitions or loops.
2 Returns Nothing Unlike eval(), exec() doesn’t return a value.
Executes in Custom You can specify global and local scopes using
3
Contexts dictionaries.
Dynamically Define Commonly used in metaprogramming or configuration-
4
Code driven pipelines.
Avoid using with untrusted input due to security
5 Use with Caution
vulnerabilities.
# Define code block as a string (simulating dynamic input)
code_block = """
learning_rate = 0.001
epochs = 5
print("Training will run for", epochs, "epochs at LR =", learning_rate)
"""
# Execute the code
exec(code_block)
# Output:
# Training will run for 5 epochs at LR = 0.001
# Explanation:
# The exec() function executes the multi-line string as Python code.
Training will run for 5 epochs at LR = 0.001
21. filter()
Point Description
The filter() function is used to filter elements in an iterable based on a
Use Case condition provided by a function. It returns an iterator containing only the
elements for which the function returns True.
Syntax filter(function, iterable)
Parameters function (Required) — A function that defines the filtering condition.
iterable (Required) — Any iterable (like a list, tuple, or set) to apply the
filter to.
Useful Information
No. Point Description
1 Returns an Iterator Must convert to list/tuple to view results directly.
Function Must Return
2 The function should return True for items to keep.
Boolean
3 Lazy Evaluation Items are processed only when needed.
Often Combined with Lambda functions simplify inline condition
4
Lambda definitions.
Accepts lists, tuples, sets, dictionaries, and even
5 Works with Any Iterable
generators.
# Sample dataset of candidate ages
candidate_ages = [15, 12, 17, 18, 25, 36]
# Define filtering logic: Accept only those aged 18 or older
def is_eligible(age):
return age >= 18
# Apply filter to the list
eligible_candidates = filter(is_eligible, candidate_ages)
# Convert the result to a list and print
print(list(eligible_candidates))
# Output:
# [18, 25, 36]
[18, 25, 36]
22. float()
Point Description
The float() function is used to convert a valid numeric value or string into
Use Case
a floating-point number (a number with decimals).
Syntax float(value)
value (Required) — A number or a numeric string to be converted into a
Parameter
float.
Useful Information
No. Point Description
Works with Integers and Accepts both whole numbers and numeric strings
1
Strings like "3.14".
Returns Float Converts the input into a number with decimal
2
Representation precision.
# Convert an integer into a floating-point number
int_val = 5
float_val = float(int_val)
print(float_val)
# Output:
# 5.0
# Convert a numeric string into a float
string_val = "5.300"
float_val_str = float(string_val)
print(float_val_str)
# Output:
# 5.3
5.0
5.3
23. format()
Point Description
The format() function converts a given value into a formatted string based
Use Case
on a specified format pattern.
Syntax format(value, format_spec)
Parameter value (Required) — The value to format.
format_spec (Required) — A string defining how the value should be
formatted.
Common Format Specifiers
Specifier Description
< Left-align the text within the available space.
> Right-align the text within the available space.
^ Center-align the text within the available space.
+ Prefix positive numbers with +, negative with -.
- Show only - for negative values (default behavior).
(space) Prefix a space for positive numbers.
, Add comma as a thousand separator (e.g., 1,000).
_ Add underscore as a thousand separator (e.g., 1_000).
b Binary format.
Specifier Description
c Unicode character representation.
d Decimal (base-10) integer.
e/E Scientific notation (lower or upper case).
f/F Fixed-point number (with or without capital F).
g/G General number formatting.
o Octal format.
x/X Hexadecimal format (lower or upper case).
n Number format based on current locale.
% Percentage format.
# Format a floating-point value as a percentage
confidence_score = 0.85
formatted_confidence = format(confidence_score, '%')
print(formatted_confidence)
# Output:
# 85.000000%
# Format an integer to hexadecimal
user_id = 255
hex_user_id = format(user_id, 'x')
print(hex_user_id)
# Output:
# ff
# Format a large number with comma separator (for better readability in
reports)
total_parameters = 12345678
formatted_params = format(total_parameters, ',')
print(formatted_params)
# Output:
# 12,345,678
85.000000%
ff
12,345,678
24. frozenset()
Point Description
The frozenset() function creates an immutable set object, meaning its
Use Case contents cannot be changed after creation. It is hashable and can be used
as keys in dictionaries or added to sets.
Syntax frozenset(iterable)
iterable (Required) — Any iterable collection (like list, set, tuple, dictionary,
Parameter
etc.) whose elements will be used to construct the frozenset.
Useful Information
No. Point Description
Unlike a normal set, you cannot add or remove items from a
1 Immutable
frozenset.
Because of its immutability, a frozenset can be used as a
2 Hashable
dictionary key or as an element in another set.
Removes Like a regular set, duplicate elements from the input iterable are
3
Duplicates removed.
Accepts Any Input can be a list, tuple, string, dictionary (only keys are used),
4
Iterable or another set.
# Sample input
feature_tags = ['deep_learning', 'transformer', 'attention',
'transformer', 'nlp']
# Create an immutable version of feature tags
immutable_tags = frozenset(feature_tags)
# Output the frozen set
print("Frozen feature tags:", immutable_tags)
# Attempt to modify the frozenset (this will raise an error)
# immutable_tags.add('reinforcement_learning') # Uncommenting this line
will cause an AttributeError
# Output:
# Frozen feature tags: frozenset({'attention', 'nlp', 'transformer',
'deep_learning'})
Frozen feature tags: frozenset({'attention', 'transformer',
'deep_learning', 'nlp'})
25. getattr()
Point Description
The getattr() function retrieves the value of a specified attribute from an
Use Case
object.
Syntax getattr(object, attribute_name, default_value)
Parameter object (Required) — The object from which you want to fetch the attribute.
attribute_name (Required) — The name (string) of the attribute you want
to retrieve.
default_value (Optional) — Value to return if the attribute is not found
(prevents AttributeError).
Useful Information
No. Point Description
Useful when attribute names are not known beforehand
1 Dynamic Access
(e.g., from config files or user input).
If the attribute doesn't exist, you can provide a default
2 Fallback Option
value to avoid exceptions.
Works on Classes & You can use getattr() on both class-level and instance-
3
Instances level attributes.
No. Point Description
Avoids runtime errors by handling missing attributes
4 Prevents Crashes
gracefully.
# Example 1: Fetching a Valid Attribute
# Define a simple configuration class for an AI model
class ModelConfig:
model_name = "BERT"
version = "v1.0"
task = "text-classification"
# Retrieve an existing attribute
model_task = getattr(ModelConfig, 'task')
print("Model Task:", model_task)
# Output:
# Model Task: text-classification
Model Task: text-classification
# Example 2: Retrieving a Non-Existing Attribute with Default Fallback
# Trying to access a non-existing attribute 'dropout'
# Provide default value to avoid error
dropout_value = getattr(ModelConfig, 'dropout', 'not configured')
print("Dropout:", dropout_value)
# Output:
# Dropout: not configured
Dropout: not configured
26. globals()
Point Description
The globals() function returns a dictionary representing the current
Use Case global symbol table. This is where all global variables and functions are
stored during program execution.
Syntax globals()
Parameters This function takes no parameters.
Useful Information
No. Point Description
Returns Global The result is a dictionary containing all global identifiers like
1
Scope functions, classes, and variables.
Useful for dynamically modifying or accessing global variables
2 Dynamic Access
during runtime.
Includes Special Contains Python’s built-in special variables such as
3
Keys '__name__', '__file__', and '__doc__'.
Avoid excessive use in production code—it can lead to hard-to-
4 Caution
maintain and error-prone logic.
# Example 1: View Global Symbol Table
# Global variable used in model setup
model_name = "TransformerXL"
# Retrieve the global symbol table
global_scope = globals()
# Access the value of a global variable using its name
print("Model Name:", global_scope["model_name"])
# Output:
# Model Name: TransformerXL
Model Name: TransformerXL
# Example 2: Check for Script Metadata in Globals
# Print special script-related global variables
globals_dict = globals()
# Check if script metadata like '__name__' exists
print("__name__:", globals_dict["__name__"])
# Output:
# __name__: __main__
__name__: __main__
27. hasattr()
Point Description
The hasattr() function checks whether a given object contains a specific
Use Case
attribute. It returns True if the attribute exists; otherwise, it returns False.
Syntax hasattr(object, attribute)
Parameters object (Required) — The object to inspect.
attribute (Required) — A string representing the name of the attribute to
check.
Useful Information
No. Point Description
Attribute Existence Helps safely check if an object has a specific property
1
Check before accessing it.
No. Point Description
Widely used in class-based programming for reflection and
2 Common in OOP
conditional logic.
3 Prevents Errors Avoids potential AttributeError by checking first.
4 Input Must Be String The attribute name must be passed as a string.
# Define a simple class representing a student
class Student:
name = "Alice"
age = 20
# Check if the Student class has certain attributes
print(hasattr(Student, 'name')) # True - because 'name' exists
print(hasattr(Student, 'grade')) # False - 'grade' is not defined
# Output:
# True
# False
True
False
28. hash()
Point Description
The hash() function returns the hash value (an integer) of an object, which
Use Case is useful when storing objects in hash-based collections like dictionaries
and sets.
Syntax hash(object)
object (Required) — Any hashable object such as strings, numbers, or
Parameter
tuples (with only hashable items).
Useful Information
No. Point Description
Works on Only hashable (immutable) types like int, float, str, and
1
Immutable Types tuples (with immutable elements) are accepted.
Enables Dictionary Hash values allow objects to be used as keys in
2
and Set Keys dictionaries or elements in sets.
Consistent During Hashes remain consistent during a program's execution but
3
Execution may differ between runs (due to hash randomization).
You can override __hash__() in user-defined classes to
4 Custom Classes
define custom hashing logic.
# Example 1: Hash a String
# Get hash value of a string
string_name = "Deep learning"
print(hash(string_name))
# Output: Varies depending on Python session
-6144713030499523922
# Example 2: Hash a Tuple
# Hash a tuple (must contain only hashable elements)
coordinates = (10, 20)
print(hash(coordinates))
# Output: Varies each session but consistent during runtime
-4873088377451060145
# Example 3: Hash in Dictionary
# Define a configuration ID using a tuple as a key
model_config = {
("resnet", 50): "ImageNet ResNet-50",
("transformer", 12): "BERT Base"
}
# Access a value using a tuple key (hash internally used)
print(model_config[("resnet", 50)])
# Output:
# ImageNet ResNet-50
ImageNet ResNet-50
29. help()
Point Description
The help() function launches Python's built-in help utility, which provides
Use Case documentation for objects, modules, classes, functions, keywords, and
more.
Syntax help(object)
object (Optional) — The object you want help documentation for (can be a
Parameter module, class, function, string keyword, etc.). If no argument is passed, it
enters interactive help mode.
Useful Information
No. Point Description
If called without arguments, enters an interactive help shell.
1 Interactive Mode
Type quit to exit.
Ideal for quickly checking documentation, method
2 Useful for Learning
signatures, and usage.
Works with
3 Supports help on Python keywords like for, def, class, etc.
Keywords
No. Point Description
Works in Terminal Best used in command-line or script environment; limited
4
or IDE output in some IDE consoles.
# Example 1: Get Help on Built-in Type
# Get help on the built-in list class
help(list)
# Output: Detailed documentation about list methods like append(),
extend(), pop(), etc.
# Example 2: Help on a Custom Function
# Define a custom function
def greet(name):
"""Returns a greeting message."""
return f"Hello, {name}!"
# Get help documentation
help(greet)
# Output:
# Help on function greet in module __main__:
# greet(name)
# Returns a greeting message.
Help on function greet in module __main__:
greet(name)
Returns a greeting message.
# Example 3: Help on Python Keyword
# Help on Python keyword 'for'
help("for")
# Output: Explains the usage and syntax of the 'for' loop in Python
# Example 4: Launch Interactive Help Mode
# Launch help console (command-line only)
help()
# You can then type in 'str', 'dict', 'import', etc., and explore help
interactively
30. hex()
Point Description
The hex() function is used to convert an integer into its hexadecimal
Use Case
representation (base-16). The resulting string starts with the prefix 0x.
Syntax hex(number)
number (Required) — An integer value to be converted to a hexadecimal
Parameter
string.
Useful Information
No. Point Description
1 Returns a String The result is always a string starting with '0x'.
Works Only on
2 The input must be an integer; otherwise, a TypeError is raised.
Integers
Useful in low-level programming, memory addresses,
Commonly
3 cryptography, and when working with color codes or bitwise
Used In
operations.
# Convert 16 to hexadecimal
value = 16
hex_value = hex(value)
print(f"The hexadecimal form of {value} is: {hex_value}")
# Output:
# The hexadecimal form of 16 is: 0x10
The hexadecimal form of 16 is: 0x10
31. id()
Point Description
The id() function returns the unique identity number (memory address) of
Use Case
an object. This identity is constant for the object’s lifetime.
Syntax id(object)
object (Required) — Any object such as a number, string, list, tuple,
Parameter
dictionary, function, class instance, etc.
Useful Information
No. Point Description
1 Identity is Unique The id() is unique and constant for the life of the object.
Represents Memory The returned integer is typically the memory address
2
Address where the object is stored.
Same Objects, Same Immutable objects like small integers or strings may
3
ID reuse IDs internally for optimization.
Helpful For Can be used to check if two variables point to the same
4
Debugging object in memory.
# Create two variables pointing to the same list
a = [1, 2, 3]
b = a
# Compare their memory addresses
print(id(a)) # Example: 140093760517952
print(id(b)) # Same as above since both point to the same list
# Output: 'a' and 'b' reference the same object in memory.
132871744035520
132871744035520
32. input()
Point Description
The input() function is used to receive input from the user during
Use Case
program execution.
Syntax input(prompt)
prompt (Optional) — A string message displayed to the user before input is
Parameter
accepted.
Useful Information
No. Point Description
Always Returns a No matter what the user enters, the return type is always
1
String str.
Type Conversion If you need numeric input, you must explicitly convert it
2
Required using int(), float(), etc.
Prompt Message is You can display a message with input(), or just use it
3
Optional alone.
Common in CLI Frequently used to collect data interactively in console-
4
Programs based scripts.
# Example 1: Simple Name Prompt
# Ask the user to enter their name
user_name = input("What is your name? ")
# Greet the user using their input
print("Welcome to Intensity Coding, " + user_name + "!")
# Example Output (if user enters "Aditi"):
# What is your name? Aditi
# Welcome to Intensity Coding, Aditi!
What is your name? Aditi
Welcome to Intensity Coding, Aditi!
# Example 2: Convert Input to Integer for Age Calculation
# Prompt user to enter their age
age_input = input("Enter your age: ")
# Convert input from string to integer
age = int(age_input)
# Use the age in a simple calculation
print("In 5 years, you will be", age + 5)
# Example Output (if user enters "25"):
# Enter your age: 25
# In 5 years, you will be 30
Enter your age: 25
In 5 years, you will be 30
33. int()
Point Description
The int() function is used to convert a specified value into an integer
Use Case
(whole number).
Syntax int(value, base)
Point Description
Parameters value (Required) — A number or string that represents an integer or float.
base (Optional) — The numeric base for conversion when the value is a
string (default is 10).
Useful Information
No. Point Description
Converts Float to
1 Decimal values are truncated (not rounded).
Integer
2 Parses Strings Can convert string numbers like "101" to integers.
Supports Base Useful for binary, octal, or hexadecimal conversions
3
Conversion using the base parameter.
Raises Error on Invalid Providing an invalid string (like 'abc') will raise a
4
Input ValueError.
# Example 1: Convert Float to Integer
# Convert a float to an integer
num = int(7.9)
print(num)
# Output:
# 7
# Example 2: Convert String to Integer
# Convert a numeric string to an integer
str_num = "45"
converted = int(str_num)
print(converted)
# Output:
# 45
45
# Example 3: Convert Binary String Using Base
# Convert binary (base 2) string to integer
binary_str = "1010"
result = int(binary_str, 2)
print(result)
# Output:
# 10
# Explanation: '1010' in binary = 10 in decimal
10
34. isinstance()
Point Description
The isinstance() function checks whether a given object belongs to a
Use Case
specified type or class.
Syntax isinstance(object, type)
Return True if the object is an instance of the specified type/class (or any from a
Type tuple of types), otherwise False.
Parameter object (Required) - The object whose type you want to verify.
type (Required) - A type or class (e.g., int, str) or a tuple of types to
check against.
Useful Information
No. Detail Explanation
1 Multiple Types Pass a tuple to check if the object matches any of the types.
Class-Based
2 Can be used with custom classes and user-defined objects.
Check
Commonly used in validation, type-safe programming, and
3 Type Safety
polymorphic behavior.
# Example 1: Basic Type Check
# Check if a number is an integer
num = 47
print(isinstance(num, int)) # Output: True
True
# Example 2: Check Against Multiple Types
# Check if a value matches any of the listed types
value = "Intensity"
result = isinstance(value, (str, int, list))
print(result) # Output: True
True
# Example 3: Check Custom Class Instance
# Define a class
class ModelConfig:
model_type = "Transformer"
layers = 12
# Create an instance
config = ModelConfig()
# Check if config is an instance of ModelConfig
print(isinstance(config, ModelConfig)) # Output: True
True
# Example 4: Invalid Type Check
# Check if a float is an instance of list
value = 3.14
print(isinstance(value, list)) # Output: False
False
35. issubclass()
Point Description
The issubclass() function checks whether a class is a derived subclass
Use Case
of another class.
Syntax issubclass(class, classinfo)
Return Returns True if the first class is a subclass (direct or indirect) of the
Type second class or any class in a tuple. Otherwise, returns False.
Parameter class (Required) The class you want to test.
classinfo (Required) A class object or a tuple of classes to test against.
Useful Information
No. Detail Explanation
Works only with
1 Both parameters must be class types, not instances.
classes
No. Detail Explanation
2 Inheritance check Returns True even for multilevel inheritance.
You can pass a tuple of classes to check against multiple
3 Tuple Support
base classes.
# Example 1: Basic Subclass Check
# Base class
class BaseModel:
pass
# Derived class
class CustomModel(BaseModel):
pass
# Check if CustomModel is a subclass of BaseModel
print(issubclass(CustomModel, BaseModel)) # Output: True
True
# Example 2: Check With Unrelated Classes
class Dataset:
pass
class Trainer:
pass
print(issubclass(Trainer, Dataset)) # Output: False
False
# Example 3: Using Tuple of Classes
class A: pass
class B: pass
class C(A): pass
# Check if class C is a subclass of either A or B
print(issubclass(C, (A, B))) # Output: True
True
36. iter()
Point Description
The iter() function returns an iterator object from a given iterable. It can
Use Case also be used with a sentinel value to create an iterator from a callable that
stops when the sentinel value is returned.
Syntax iter(object) or iter(callable, sentinel)
Parameter object (Required) — An iterable object (e.g., list, tuple, string, etc.)
sentinel (Optional) — A value which, when returned by the callable, signals
the end of iteration
Useful Information
No. Point Description
1 Converts to Iterator Transforms any iterable (like list, string, etc.) into an iterator.
The returned iterator is consumed using the built-in next()
2 Used with next()
function.
Supports Callable If a callable and a sentinel are provided, the iteration
3
with Sentinel continues until the callable returns the sentinel value.
4 Common in Loops Often used internally in for loops and comprehensions.
# Example 1: Creating an iterator from a list
# Create an iterable list
fruits_name = ["apple", "mango", "banana"]
# Convert the list into an iterator
fruit_iterator = iter(fruits_name)
# Retrieve elements one by one using next()
print(next(fruit_iterator)) # Output: apple
print(next(fruit_iterator)) # Output: mango
print(next(fruit_iterator)) # Output: banana
apple
mango
banana
# Example 2: Using iter() with a sentinel value
# Define a callable object (function that returns user input)
def input_reader():
return input("Enter a number (type 'exit' to stop): ")
# Create an iterator that ends when 'exit' is returned
input_iter = iter(input_reader, 'exit')
# Process the input until the sentinel is reached
for val in input_iter:
print("You entered:", val)
# Example Input:
# Enter a number (type 'exit' to stop): 123
# You entered: 123
# Enter a number (type 'exit' to stop): 99
# You entered: 99
# Enter a number (type 'exit' to stop): exit
Enter a number (type 'exit' to stop): 123
You entered: 123
Enter a number (type 'exit' to stop): 99
You entered: 99
Enter a number (type 'exit' to stop): exit
37. len()
Point Description
The len() function returns the total number of elements in a sequence or
Use Case
collection such as strings, lists, tuples, dictionaries, sets, etc.
Syntax len(object)
object (Required) — Any sequence (e.g., string, list, tuple) or collection
Parameter
(e.g., dictionary, set).
Useful Information
No. Point Description
Works with Multiple Can be used on strings, lists, tuples, dictionaries, sets,
1
Types etc.
For strings, it counts characters; for lists, it counts
2 Measures Size
elements; for dictionaries, it counts key-value pairs.
3 Required in Loops Commonly used to control loop ranges and validations.
Cannot Be Used on Raises a TypeError if the object doesn't support
4
Non-Iterable Types __len__() internally.
# Example 1: Length of a string
# String input
message = "Welcome to Intensity Coding"
# Get number of characters in the string
length = len(message)
print(length)
# Output: 27
27
# Example 2: Length of a list
topics = ["NLP", "Computer Vision", "Reinforcement Learning", "Generative
Models"]
# Get number of items in the list
count = len(topics)
print(count)
# Output: 4
# Example 3: Length of a dictionary
# Dictionary containing model names
models = {
"CNN": "Image classification",
"RNN": "Sequence modeling",
"Transformer": "Language tasks"
}
# Get number of key-value pairs
print(len(models))
# Output: 3
38. list()
Point Description
The list() function is used to create a new list object from an iterable.
Use Case
Lists are ordered, mutable (changeable), and allow duplicate values.
Syntax list(iterable)
Point Description
iterable (Optional) — Any iterable object (such as a string, tuple, set, or
Parameter
another list). If no argument is provided, it creates an empty list.
Useful Information
No. Point Description
Can convert strings, tuples, sets, and other iterables into
1 Converts Iterables
lists.
2 Creates Empty Lists If no argument is passed, an empty list [] is created.
Once created, lists can be modified—items can be added,
3 Lists Are Mutable
removed, or updated.
List Elements The order of elements in the iterable is preserved in the
4
Maintain Order list.
# Example 1: Convert a tuple to a list
topics = ('NLP', 'Vision', 'GANs')
topics_list = list(topics)
print(topics_list)
# Output: ['NLP', 'Vision', 'GANs']
# Example 2: Create a list from a string
text = "AI"
result = list(text)
print(result)
# Output: ['A', 'I']
# Example 3: Create an empty list
model_configs = list()
print(model_configs)
# Output: []
['NLP', 'Vision', 'GANs']
['A', 'I']
[]
39. locals()
Point Description
The locals() function provides access to the current local symbol table in
Use Case the form of a dictionary. It is useful for introspection, debugging, or
understanding what variables exist in a local scope.
Syntax locals()
Parameter None — This function does not accept any arguments.
Useful Information
No. Point Description
Returns variables and definitions that exist in the local
1 Local Scope Only
scope where it is called.
Output is a Keys are variable names and values are their current
2
Dictionary content.
Often used inside functions to inspect or manipulate local
3 Common Use Case
variables.
Not Meant for Although it returns a modifiable dictionary, changes may
4
Modification not affect the actual local variables directly.
# Example 1: Get local variables in the current scope
# Define a function to simulate a local scope
def ai_info():
model = "Transformer"
version = 4
config = {"layers": 12, "dropout": 0.1}
# Fetch local symbol table
local_vars = locals()
print(local_vars)
# Call the function
ai_info()
# Output (example):
# {'model': 'Transformer', 'version': 4, 'config': {'layers': 12,
'dropout': 0.1}}
# Explanation: Returns all local variables as key-value pairs.
{'model': 'Transformer', 'version': 4, 'config': {'layers': 12,
'dropout': 0.1}}
# Example 2: Use locals() outside a function
# Global level usage
language = "Python"
level = "Beginner"
# View current local/global scope variables
current_scope = locals()
print(current_scope)
# Output (example):
# {'__name__': '__main__', 'language': 'Python', 'level': 'Beginner',
...}
40. map()
Point Description
The map() function applies a given function to each item in one or more
Use Case
iterables and returns a map object (an iterator).
Syntax map(function, iterable1, iterable2, ...)
Parameter function (Required) — A function that will be applied to each element.
iterable (Required) — One or more iterables (lists, tuples, etc.) to process.
Each iterable must match the number of function arguments.
Useful Information
No. Point Description
The result is a map object, which is an iterator. Use list() or
1 Returns Iterator
tuple() to view it.
Multiple You can pass more than one iterable, but the function must
2
Iterables accept the same number of arguments.
Shortest Iterable If iterables are of different lengths, iteration stops at the
3
Rule shortest.
Common in functional programming and cleaner than using
4 Functional Style
for loops for transformations.
# Example 1: Get lengths of model names
# Define a function to calculate length
def get_length(item):
return len(item)
# List of model names
models = ['GPT', 'BERT', 'Transformer']
# Apply function to each element using map
result = map(get_length, models)
# Convert the map object to list
print(result)
print(list(result))
# Output: [3, 4, 11]
# Explanation: Returns the length of each string in the list.
<map object at 0x78d89d036890>
[3, 4, 11]
# Example 2: Combine two sets
# Function to combine strings
def combine(a, b):
return f"{a}-{b}"
# Two iterables
models = ['GPT', 'BERT', 'T5']
tasks = ['NLP', 'QA', 'Summarization']
# Use map to pair each model with a task
result = map(combine, models, tasks)
# Convert to list
print(list(result))
# Output: ['GPT-NLP', 'BERT-QA', 'T5-Summarization']
# Explanation: Combines corresponding elements from both iterables.
['GPT-NLP', 'BERT-QA', 'T5-Summarization']
41. max()
Point Description
The max() function returns the item with the highest value among two or
Use Case
more values, or from within an iterable.
Syntax max(val1, val2, ...) or max(iterable)
Parameter Individual values (e.g., numbers or strings) — Compared directly.
An iterable (list, tuple, etc.) — The function returns the maximum element
within the collection.
Useful Information
No. Point Description
When comparing strings, it uses lexicographical
1 Supports Strings
(alphabetical) order.
2 Accepts Key Argument You can use key= to customize the comparison logic.
No. Point Description
Works with Numbers or Can compare direct values or elements inside lists,
3
Iterables tuples, etc.
Raises Error on Empty A ValueError is raised if the iterable is empty and no
4
Iterable default is provided.
Comparing different types (e.g., string vs. int) will raise
5 Mixed-Type Caution
an error.
# Example 1: Find maximum among numeric values
# Compare two numbers directly
result = max(15, 10)
print(result)
# Output: 15
15
# Example 2: Find max value in a tuple
scores = (12, 44, 31, 78)
# Get highest score
result = max(scores)
print(result)
# Output: 78
78
# Example 3: Max from strings (alphabetical comparison)
# Compare string values
names = ["Raj", "Dev", "Virat"]
# Find alphabetically last name
result = max(names)
print(result)
# Output: Virat
Virat
42. memoryview()
Point Description
The memoryview() function creates a memory view object that allows
Use Case direct access to the internal data of a byte-based object without copying it.
Useful for handling large binary data efficiently.
Syntax memoryview(object)
Parameter object (Required) — A bytes or bytearray object.
Useful Information
No. Point Description
Provides a way to access data without copying, which is
1 No Data Copy
memory-efficient for large binary files.
Read and Write (for Supports read/write access for bytearray, read-only for
2
bytearray) bytes.
3 Indexable You can access each byte using indexing.
4 Slicing Support Supports slicing to view parts of the memory.
5 Not for Strings Works only with bytes or bytearray, not plain str objects.
# Example 1: Create a memory view from bytes
# Create a bytes object
data = b"Intensity"
# Get a memoryview of the bytes
mem_view = memoryview(data)
print(mem_view) # Output: <memory at 0x...>
print(mem_view[0]) # Output: 73 -> ASCII of 'I'
print(mem_view[1]) # Output: 110 -> ASCII of 'n'
<memory at 0x78d89d09bac0>
73
110
# Example 2: Modify bytearray using memoryview
# Create a mutable bytearray
buffer = bytearray(b"AI")
# Create a memoryview of it
view = memoryview(buffer)
# Modify the first byte (replace 'A' -> 'B')
view[0] = 66 # 66 is ASCII of 'B'
print(buffer) # Output: bytearray(b'BI')
bytearray(b'BI')
# Example 3: Slice and inspect memory
# Create a memoryview over a bytearray
buffer = bytearray(b"coding")
view = memoryview(buffer)
# Slice the memoryview and convert to bytes
sub_view = view[1:5]
print(bytes(sub_view)) # Output: b"odin"
b'odin'
43. min()
Point Description
The min() function returns the smallest item among the arguments passed
Use Case
or from the items in an iterable. Works with numbers and strings.
Syntax min(val1, val2, ..., valN) or min(iterable)
Parameter Either multiple values or a single iterable like a list, tuple, etc.
Useful Information
No. Point Description
Accepts Iterable or Works with both iterables (e.g., lists, tuples) and
1
Multiple Arguments multiple individual arguments.
Supports Different Data Works with numbers and strings (uses
2
Types ASCII/lexicographic comparison for strings).
Can be extended using the key argument to
3 Custom Comparison
customize how values are compared.
Raises Error on Empty If the iterable is empty and no default is provided, a
4
Input ValueError is raised.
# Example 1: Finding the smallest number
x = min(5, 15, 2, 8)
print(x)
# Output: 2
2
# Example 2: Using min() on strings
# Alphabetical comparison - finds the smallest based on lexicographical
order
names = ["Zara", "Liam", "Ava", "Noah"]
x = min(names)
print(x)
# Output: 'Ava' (since 'A' comes before others alphabetically)
Ava
# Example 3: min() with a tuple of numbers
# Tuple input
scores = (22, 45, 19, 88)
lowest = min(scores)
print(lowest)
# Output: 19
19
# Example 4: Using key argument for custom comparison
# Find the shortest string using key=len
models = ["ResNet", "GPT", "EfficientNet", "VGG"]
shortest_name = min(models, key=len)
print(shortest_name)
# Output: 'GPT'
GPT
44. next()
Point Description
The next() function retrieves the next item from an iterator. If the iterator is
Use Case
exhausted, a default value can be returned instead of raising an error.
Syntax next(iterator)or next(iterator, default)
iterator (Required) — An object with an __iter__() and __next__()
Parameter
method.
default (Optional) — A value returned when the iterator is exhausted.
Useful Information
No. Point Description
1 Iterator Only Works only on iterator objects created using iter().
Raises If no default value is provided and the iterator is exhausted, a
2
StopIteration StopIteration error is raised.
Default for Use the default argument to avoid errors and return a
3
Safety fallback value.
# Example 1: Basic Usage with iter()
# Create an iterator from a list of AI model names
models = iter(["GPT", "BERT", "T5"])
# Manually access each element using next()
print(next(models)) # Output: GPT
print(next(models)) # Output: BERT
print(next(models)) # Output: T5
GPT
BERT
T5
# Example 2: Using next() with a default fallback value
# List of data types used in ML
types = iter(["Tensor", "Array", "Matrix"])
# Access items and provide a default for when the list is exhausted
print(next(types, "None")) # Output: Tensor
print(next(types, "None")) # Output: Array
print(next(types, "None")) # Output: Matrix
print(next(types, "None")) # Output: None (since all elements are
already consumed)
Tensor
Array
Matrix
None
# Example 3: Avoiding `StopIteration` in AI Data Stream
# Simulating batch data from a generator
def data_stream():
yield "Batch 1"
yield "Batch 2"
stream = data_stream()
# Safe access using next() with default
print(next(stream, "No more data")) # Output: Batch 1
print(next(stream, "No more data")) # Output: Batch 2
print(next(stream, "No more data")) # Output: No more data
Batch 1
Batch 2
No more data
45. object()
Point Description
The object() function creates a basic empty object. It’s the most
Use Case
fundamental base class in Python, from which all other classes inherit.
Syntax object()
Parameter None — This function does not take any parameters.
Useful Information
No. Point Description
You cannot dynamically assign new attributes or methods
1 Immutable Object
to an object() instance.
Every class in Python inherits from the base object class
2 Base of All Classes
implicitly or explicitly.
Methods like __str__(), __eq__(), and __class__() are
3 Default Methods
inherited from object.
Used in Class class MyClass(object) is a common pattern to indicate
4
Inheritance inheritance from the base class.
Lightweight & Useful for creating simple placeholders or identity
5
Minimal comparisons.
# Example 1: Creating and Inspecting an `object` Instance
# Creating an empty object using object()
empty = object()
# View all built-in attributes and methods inherited from base object
print(dir(empty))
# Output: ['__class__', '__delattr__', '__dir__', '__doc__', ...,
'__str__', '__subclasshook__']
# Explanation: These are the default attributes every Python object has.
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__']
# Example 2: Attempting to Add Attributes (Fails)
# Trying to add attributes to a base object
obj = object()
# This will raise an AttributeError since object() is immutable and
doesn't allow setting attributes
try:
[Link] = "AI Model"
except AttributeError as e:
print("Error:", e)
# Output:
# Error: 'object' object has no attribute 'name'
Error: 'object' object has no attribute 'name'
# Example 3: Base Class for Inheritance
# Define a custom class inheriting from base object explicitly
class ModelConfig(object):
def __init__(self):
[Link] = "Transformer"
[Link] = 12
config = ModelConfig()
print([Link]) # Output: Transformer
print([Link]) # Output: 12
Transformer
12
46. oct()
Point Description
The oct() function converts a given integer into its octal (base-8)
Use Case
representation as a string.
Syntax oct(number)
number (Required) — An integer value that you want to convert to an octal
Parameter
string.
Useful Information
No. Point Description
The returned string always starts with "0o", indicating an octal
1 Prefix Format
number.
Integer Only integers can be passed to oct(). Floating-point or string
2
Required inputs will raise a TypeError.
Common Use Often used in low-level programming, file permissions (like UNIX
3
Case chmod), or data encoding.
You can convert the result back to an integer using
4 Reversible
int(octal_string, 8).
# Example 1: Convert Decimal to Octal
# Convert a decimal number to its octal representation
number = 15
octal_value = oct(number)
print(octal_value)
# Output: 0o17
0o17
47. open()
Point Description
The open() function is used to open a file and return a file object, which
Use Case
allows reading, writing, or appending based on the selected mode.
Syntax open(file, mode)
Parameter file (Required) — The file path (relative or absolute) to open.
mode (Optional) — A string indicating how the file should be opened.
Defaults to "r" (read mode).
File Open Modes in Python
Mode Description
"r" Read-only. Default mode. Error if file doesn't exist.
"a" Append mode. Creates file if it doesn't exist.
"w" Write mode. Overwrites file if it exists, creates if not.
"x" Exclusive creation. Error if file already exists.
Text vs Binary Mode
Mode Description
"t" Text mode (default). Use for plain text files.
"b" Binary mode. Use for binary files like images or models.
File Modes with Variations
Mode Purpose
r Read text. Error if file doesn't exist.
rb Read binary. Error if file doesn't exist.
r+ Read and write text. Error if file doesn't exist.
rb+ Read and write binary. Error if file doesn't exist.
w Write text. Overwrites or creates a new file.
wb Write binary. Overwrites or creates a new file.
w+ Read and write text. Overwrites or creates a new file.
wb+ Read and write binary. Overwrites or creates a new file.
a Append text. Creates file if not present. Inserts data at end of the file.
ab Append binary. Creates file if not present. Inserts data at end of the file.
a+ Read and append text. Creates file if not present. Inserts data at end of the file.
Read and append binary. Creates file if not present. Inserts data at end of the
ab+
file.
Useful Information
No. Point Description
If no mode is specified, the file is opened in "r" (read) and "t"
1 Default Mode
(text) mode.
2 Binary vs Text Use "b" for binary files like images, and "t" for text files.
It's good practice to use a with statement for automatic
3 Safe Handling
resource management.
File Object
4 Common methods: read(), write(), readlines(), close().
Methods
# Example 1: Reading a File (Basic Read Mode)
# Open and read a text file using default 'rt' mode (read text)
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# Output:
# (Displays content of [Link] if it exists)
cat
dog
bird
# Example 2: Writing Data to a File (Write Mode)
# Overwrite the file with new content using write mode
with open("[Link]", "w") as file:
[Link]("cat")
# Output: Content written to [Link]
# Example 3: Appending to a File (Append Mode)
# Append a new line without erasing existing content
with open("[Link]", "a") as file:
[Link]("\ndog")
# Output: Appends to [Link]
# Example 4: Binary File Handling (Binary Read Mode)
# Open an image file in binary mode
with open("[Link]", "rb") as image_file:
binary_data = image_file.read()
print(type(binary_data))
# Output:
# <class 'bytes'>
<class 'bytes'>
48. ord()
Point Description
The ord() function returns the Unicode code point (integer representation)
Use Case
of a given character.
Syntax ord(character)
Parameter character (Required) — A string containing a single Unicode character.
Useful Information
No. Point Description
Input Must Be One You must pass only a single character; multi-character
1
Character strings raise a TypeError.
Works with any character in the Unicode standard,
2 Unicode Support
including non-English characters.
Useful for Encoding
3 Often used in encryption, sorting, and data processing.
Tasks
# Example 1: Convert a Lowercase Letter to Unicode
# Get the Unicode value of the character 'i'
x = ord("i")
print(x)
# Output:
# 105
105
# Example 2: Unicode of a Special Symbol
# Get the Unicode code point of the dollar sign
symbol_code = ord("$")
print(symbol_code)
# Output:
# 36
36
# Example 3: Unicode of a Non-English Character
# Get Unicode value of a non-English letter
char_code = ord("अ") # Hindi letter 'A'
print(char_code)
# Output:
# 2309
2309
49. pow()
Point Description
The pow() function computes the power of a number. It returns x raised to
Use Case the power of y, i.e., x ** y. If a third argument z is provided, it returns (x
** y) % z, which is useful in modular arithmetic.
Syntax pow(x, y, z)
Parameter x (Required) — The base number.
y (Required) — The exponent.
z (Optional) — A number to perform modulo operation with the result of x
** y.
Useful Information
No. Point Description
Equivalent to x ** y when the third parameter is
1 Works as Exponentiation
not given.
Efficiently calculates (x ** y) % z, even for large
2 Modular Arithmetic
numbers.
Works with Integers and Although modular form requires all three values to
3
Floats be integers.
# Example 1: Simple Power Calculation
# Calculate 2 raised to the power of 3
result = pow(2, 3)
print(result)
# Output:
# 8
# Example 2: Power with Modulo Operation
# Calculate (4 ** 3) % 5 using the third parameter
mod_result = pow(4, 3, 5)
print(mod_result)
# Output:
# 4
8
4
50. print()
Point Description
The print() function outputs the given message or object(s) to the
Use Case standard output (typically the screen). It automatically converts objects to
strings before printing.
Point Description
print(object1, object2, ..., sep='separator', end='end',
Syntax
file=file, flush=flush)
object(s) (Required) — One or more objects to print (converted to
Parameters
strings).
sep (Optional) — String inserted between objects. Default is a space ' '.
end (Optional) — String added after the last object. Default is newline
'\n'.
file (Optional) — The output stream (e.g., a file object). Default is
[Link].
flush (Optional) — Boolean to force flushing the output buffer. Default is
False.
Useful Information
No. Point Description
Converts
1 All objects passed are converted to string if not already.
Automatically
Supports printing multiple items separated by custom
2 Multiple Outputs
delimiters.
Custom Line Use end='' to avoid line breaks or add custom line
3
Endings endings.
Supports writing output to a file by assigning
4 File Output
file=open(...).
Buffered or Use flush=True to force immediate screen output, useful
5
Unbuffered in real-time systems.
# Example 1: Basic Printing
# Print a simple message
print("Welcome to Intensity Coding")
# Output:
# Welcome to Intensity Coding
Welcome to Intensity Coding
# Example 2: Printing Multiple Objects
# Print multiple strings with default space separator
print("Machine", "Learning", "Tutorial")
# Output:
# Machine Learning Tutorial
Machine Learning Tutorial
# Example 3: Using Custom Separator and End
# Using a custom separator and ending with a question mark
print("How", "are", "you", sep="---", end="?")
# Output:
# How---are---you?
How---are---you?
# Example 4: Printing a Tuple
# Print a tuple as a single object
items = ("Machine", "Learning", "Tutorial")
print(items)
# Output:
# ("Machine", "Learning", "Tutorial")
('Machine', 'Learning', 'Tutorial')
# Example 5: Redirecting Output to a File
# Write printed text to a file instead of console
with open("[Link]", "w") as f:
print("Logging from Intensity Coding", file=f)
# Output: Written to [Link]
51. property()
Point Description
The property() function is used to define managed attributes in a class. It
Use Case allows the use of methods as if they were attributes, enabling
encapsulation and control over getting, setting, and deleting values.
Syntax property(fget=None, fset=None, fdel=None, doc=None)
Parameter fget (Optional) – Function for getting the attribute.
fset (Optional) – Function for setting the attribute.
fdel (Optional) – Function for deleting the attribute.
doc (Optional) – A string that acts as the docstring for the property.
Useful Information
No. Point Description
Mainly used within class definitions to define controlled
1 Used in Classes
access to instance variables.
Methods wrapped using property() can be accessed
2 Acts Like Attribute
like regular attributes.
Provides a clean way to define getters, setters, and
3 Enables Encapsulation
deleters.
property() function is equivalent to using the
Alternative to
4 @property, @<prop>.setter, and @<prop>.deleter
@property Decorator
decorators.
class Student:
def __init__(self):
self._name = ""
# Getter function
def get_name(self):
return self._name
# Setter function
def set_name(self, value):
if isinstance(value, str):
self._name = value
else:
raise ValueError("Name must be a string")
# Deleter function
def del_name(self):
print("Deleting name...")
del self._name
# Creating a property
name = property(get_name, set_name, del_name, "Property for student
name")
# Using the class
s = Student()
[Link] = "Alice" # Calls set_name
print([Link]) # Calls get_name
del [Link] # Calls del_name
# Output:
# Alice
# Deleting name...
Alice
Deleting name...
52. range()
Point Description
The range() function generates an immutable sequence of numbers,
Use Case
which is often used for iterating through loops.
Syntax range(start, stop, step)
Parameters start (Optional) — The beginning of the sequence. Default is 0.
stop (Required) — The endpoint (exclusive); the sequence stops before
this value.
step (Optional) — The amount by which the sequence increments. Default
is 1.
Useful Information
No. Point Description
1 Immutable The range object is immutable and memory efficient.
2 Lazy Evaluation Values are generated on demand and not stored in memory.
Convert range to a list or tuple using list() or tuple() for
3 Can Be Casted
display.
4 Negative Steps Supports decreasing sequences using a negative step.
Common in
5 Frequently used with for loops for fixed-iteration operations.
Loops
# Example 1: Simple Range (0 to 5)
# Generate numbers from 0 to 5 (excluding 6)
for num in range(6):
print(num)
# Output:
# 0
# 1
# 2
# 3
# 4
# 5
0
1
2
3
4
5
# Example 2: Custom Start and Stop
# Generate numbers from 3 to 5
for num in range(3, 6):
print(num)
# Output:
# 3
# 4
# 5
3
4
5
# Example 3: Custom Step Value
# Generate every 2nd number from 3 to 19
for num in range(3, 20, 2):
print(num, end=' ')
# Output:
# 3 5 7 9 11 13 15 17 19
3 5 7 9 11 13 15 17 19
# Example 4: Reverse Range Using Negative Step
# Countdown from 10 to 1
for num in range(10, 0, -1):
print(num, end=' ')
# Output:
# 10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
# Example 5: Convert range to list (for display)
# Convert a range to a list for readability
sequence = list(range(1, 6))
print("Generated sequence:", sequence)
# Output:
# Generated sequence: [1, 2, 3, 4, 5]
Generated sequence: [1, 2, 3, 4, 5]
53. repr()
Point Description
The repr() function returns a string that represents the specified object in
Use Case a way that ideally could be used to recreate the object. It's primarily used
for debugging and development purposes.
Syntax repr(object)
object (Required) — Any Python object for which a developer-readable
Parameter
string representation is needed.
Useful Information
No. Point Description
Returns Developer- Typically includes quotes and escape characters to
1
Friendly Format show how the object would be typed in code.
repr() is for debugging and development; str() is for
2 Different from str()
end-user readability.
Often Used in Debug
3 Helpful for logging detailed object structures.
Logs
Automatically Used in The Python shell automatically calls repr() on output
4
Shell values.
# Example 1: Using `repr()` with a String
text = "Intensity Coding"
debug_output = repr(text)
print(debug_output)
# Output: 'Intensity Coding'
# Explanation: repr() adds quotes, showing it as a literal string.
'Intensity Coding'
# Example 2: Difference Between `str()` and `repr()`
value = 'AI\nML'
print("Using str():", str(value))
# Output: Using str(): AI
# ML
print("Using repr():", repr(value))
# Output: Using repr(): 'AI\nML'
# Explanation: str() prints the string as-is; repr() shows escape
characters.
Using str(): AI
ML
Using repr(): 'AI\nML'
54. reversed()
Point Description
The reversed() function returns an iterator that accesses the given
Use Case
sequence in the reverse order. It does not modify the original sequence.
Syntax reversed(sequence)
sequence (Required) — Any iterable that supports reverse iteration such as
Parameter
lists, tuples, strings, or custom objects with __reversed__() implemented.
Useful Information
No. Point Description
Does Not Modify Returns a reverse iterator; the original object remains
1
Original unchanged.
Only works on sequence types like lists, tuples, and
2 Works on Sequences
strings.
Must Convert to Convert to list() or tuple() to view or reuse the reversed
3
View output.
Like any iterator, once it's used up in a loop or operation, it
4 Iterator Exhaustion
must be re-created.
Functionally similar to slicing for reversing but memory-
5 Alternative to [::-1]
efficient.
# Example 1: Reverse a List Using `reversed()`
example_list = ["Machine", "Learning", "Tutorial"]
# Create a reverse iterator using reversed()
reverse_iter = reversed(example_list)
# Iterate and print each element in reverse
for i in reverse_iter:
print(i)
# Output:
# Tutorial
# Learning
# Machine
Tutorial
Learning
Machine
# Example 2: Convert Reverse Iterator to List
# Original list
items = [10, 20, 30, 40]
# Use reversed() and convert to list
reversed_list = list(reversed(items))
print("Reversed List:", reversed_list)
# Output:
# Reversed List: [40, 30, 20, 10]
Reversed List: [40, 30, 20, 10]
# Example 3: Reverse a String
# Reversing a string using reversed()
text = "intensity"
reversed_text = ''.join(reversed(text))
print("Reversed String:", reversed_text)
# Output:
# Reversed String: ytisnetni
Reversed String: ytisnetni
# Example 4: Reversed in For Loop (Tuple)
# Tuple of numbers
numbers = (1, 2, 3, 4)
# Using reversed() in a loop
for n in reversed(numbers):
print(n, end=' ')
# Output:
# 4 3 2 1
4 3 2 1
55. round()
Point Description
The round() function returns a number rounded to a specified number of
Use Case decimal places. If no decimal place is specified, it rounds to the nearest
integer.
Syntax round(number, digits=0)
Parameter number (Required) — The numeric value to be rounded.
digits (Optional) — The number of decimal places to round to. Defaults to
0 (returns an integer).
Useful Information
No. Point Description
Works with Integers and
1 Can round both whole and floating-point numbers.
Floats
2 Default Rounding If digits is not given, it rounds to the nearest integer.
No. Point Description
Python rounds ties to the nearest even number
3 Halfway Cases
(banker’s rounding).
# Example 1: Rounding to Two Decimal Places
value = 8.67892
rounded_value = round(value, 2)
print(rounded_value)
# Output: 8.68
# Example 2: Rounding Without Decimal Precision (Default)
value = 8.67892
rounded_value = round(value)
print(rounded_value)
# Output: 9
# Explanation: Rounded to the nearest whole number since no digits are
specified.
8.68
9
56. set()
Point Description
The set() function constructs a set object from an iterable. Sets are
Use Case
collections of unique elements that are unordered and unindexed.
Syntax set(iterable)
iterable (Optional) — A sequence, collection, or any iterable object (like
Parameter
lists, tuples, strings, etc.) used to populate the set.
Useful Information
No. Point Description
Automatically eliminates repeated elements from the
1 Removes Duplicates
input.
2 Unordered Structure Elements in a set do not maintain insertion order.
Supports Set
3 Can be used for union, intersection, difference, etc.
Operations
Immutable Elements Set elements must be of immutable types (e.g., numbers,
4
Only strings, tuples).
# Creating a set from a tuple of fruits
example_list = ["cat", "dog", "dog", "cat", "bird"]
unique_element = set(example_list)
print(unique_element)
# Output: {'cat', 'dog', 'bird'}
{'cat', 'dog', 'bird'}
57. setattr()
Point Description
The setattr() function allows you to dynamically assign a value to an
Use Case attribute of an object. If the attribute exists, it updates the value; if not, it
creates the attribute.
Syntax setattr(object, attribute, value)
object (Required) — The target object whose attribute will be modified or
Parameter
created.
attribute (Required) — The name of the attribute as a string.
value (Required) — The new value to assign to the attribute.
Useful Information
No. Point Description
1 Modifies Object State Useful for dynamically updating class instances.
If the attribute doesn't exist, it's created
2 Can Add New Attributes
automatically.
Works Well with
3 Often paired with getattr() for attribute control.
getattr()
# Example 1: Dynamically Update Attribute in a Class
# Define a class with default attributes
class ModelConfig:
name = "Transformer"
layers = 6
pretrained = True
# Dynamically update the 'layers' attribute
setattr(ModelConfig, 'layers', 12)
# Confirm the update using getattr()
updated_layers = getattr(ModelConfig, 'layers')
print("Updated number of layers:", updated_layers)
# Output: Updated number of layers: 12
Updated number of layers: 12
# Example 3: Add Custom Metadata to an Object
class Experiment:
pass
exp = Experiment()
# Add a custom attribute
setattr(exp, 'author', 'intensity_coding')
setattr(exp, 'version', 'v1.2')
print([Link]) # Output: intensity_coding
print([Link]) # Output: v1.2
intensity_coding
v1.2
58. slice()
Point Description
The slice() function generates a slice object that defines how elements
Use Case should be sliced from a sequence like a list, tuple, or string. This is
especially useful when passing slicing parameters programmatically.
Syntax slice(start, end, step)
Parameter start (Optional) — The index at which slicing starts (default is 0).
end (Required) — The index at which slicing ends (exclusive).
step (Optional) — Interval between each index (default is 1).
Useful Information
No. Point Description
Works with any
1 Can be used with lists, tuples, and strings.
Sequence
The slice() object mimics the behavior of slicing syntax
2 slice() vs :
seq[start:end:step].
Ideal for Dynamic Helpful when slicing needs to be computed or passed as a
3
Slicing parameter.
4 Negative Indices Supports negative indices for reverse slicing.
data = ["sample1", "sample2", "sample3", "sample4", "sample5", "sample6",
"sample7", "sample8"]
# Example 1: Basic Slice
# Slice: Start at index 0, stop before index 2
s = slice(2)
print(data[s])
# Output: ['sample1', 'sample2']
# Example 2: Middle Range Slice
# Slice elements from index 3 up to but not including 5
s = slice(3, 5)
print(data[s])
# Output: ['sample4', 'sample5']
# Example 3: Using Step for Interval Slicing
# Slice every third item from start to end of the tuple
s = slice(0, 8, 3)
print(data[s])
# Output: ['sample1', 'sample4', 'sample7']
['sample1', 'sample2']
['sample4', 'sample5']
['sample1', 'sample4', 'sample7']
59. sorted()
Point Description
The sorted() function is used to return a new sorted list from the
Use Case elements of any iterable (like a list, tuple, or dictionary), without modifying
the original.
Syntax sorted(iterable, key=None, reverse=False)
Parameters iterable (Required): The collection (like a list, tuple, etc.) to be sorted.
key (Optional): A function to customize sorting logic.
reverse (Optional): Boolean value. If True, results are sorted in
descending order.
Useful Information
Point Explanation
1. Returns a New The sorted() function does not modify the original iterable.
List Instead, it returns a new sorted list.
You can apply sorted() on any iterable—such as a list, tuple,
2. Works with All
dictionary, or string. For dictionaries, only the keys are sorted by
Iterables
default.
You can define a custom function using the key parameter to
3. Custom Sorting
control sorting behavior—like sorting by length, substring, or
with key
custom objects.
sorted() is a built-in global function, whereas .sort() is a
4. Different from
method available only on lists. Unlike .sort(), sorted() works
.sort()
with any iterable.
5. Type If the iterable contains mixed data types (e.g., both integers and
Consistency strings), sorted() will raise a TypeError, as elements cannot be
Required compared directly.
# Example 1: Sorting Alphabetically (Default)
fields = ["Name", "ID", "Department", "AI", "Score"]
# Sort alphabetically
sorted_fields = sorted(fields)
print(sorted_fields)
# Output: ['AI', 'Department', 'ID', 'Name', 'Score']
['AI', 'Department', 'ID', 'Name', 'Score']
# Example 2: Sorting Numbers in Ascending Order
numbers = (1, 7, 2)
# Sort numbers numerically in ascending order
sorted_nums = sorted(numbers)
print(sorted_nums)
# Output: [1, 2, 7]
[1, 2, 7]
# Example 3: Sorting in Descending Order
fields = ["Name", "ID", "Department", "AI", "Score"]
# Sort the tuple in reverse (descending) order
sorted_field__desc = sorted(fields, reverse=True)
print(sorted_field__desc)
# Output: ['Score', 'Name', 'ID', 'Department', 'AI']
['Score', 'Name', 'ID', 'Department', 'AI']
# Example 4: Sorting Strings by Length
fields = ["Name", "ID", "Department", "AI", "Score"]
# Sort by string length using a custom key
sorted_fields = sorted(fields, key=len)
print("Sorted by field length:", sorted_fields)
# Output: Sorted by field length: ['ID', 'AI', 'Name', 'Score',
'Department']
Sorted by field length: ['ID', 'AI', 'Name', 'Score', 'Department']
60. staticmethod()
Point Description
The staticmethod() function is used to define a method that does not
Use Case operate on class or instance data. It belongs to the class namespace but
does not access self or cls.
Syntax staticmethod(function)
Parameter function (Required) — The function to be converted into a static method.
Useful Information
No. Point Description
No Access to A static method does not access self or cls, meaning
1
Class/Instance it can't access or modify class or instance variables.
Used for Utility Often used to group related helper methods inside a
2
Functions class for organizational clarity.
Can Be Called via A static method can be accessed using the class name
3
Class/Instance or any of its instances.
Alternative to staticmethod() is rarely used directly in modern
4 @staticmethod Python; instead, the @staticmethod decorator is
Decorator preferred.
Helps in keeping logically grouped functionality inside a
Keeps Code
5 class even when it doesn’t depend on the class or
Encapsulated
instance state.
# Defining a class to demonstrate the use of staticmethod()
class DataPreprocessor:
def __init__(self, name):
[Link] = name
# Convert a regular method into a static method using @staticmethod
@staticmethod
def normalize_data(data):
"""
Normalize a list of numbers to range [0, 1].
"""
min_val = min(data)
max_val = max(data)
return [(x - min_val) / (max_val - min_val) for x in data]
# Calling the static method without creating an instance
normalized = DataPreprocessor.normalize_data([5, 10, 15])
print("Normalized Data:", normalized)
# Output:
# Normalized Data: [0.0, 0.5, 1.0]
# Alternative: Using `staticmethod()` Function Directly
class MathUtils:
def square(x):
return x * x
# Manually converting square into a static method
square = staticmethod(square)
print([Link](6)) # Output: 36
Normalized Data: [0.0, 0.5, 1.0]
36
61. str()
Point Description
The str() function is used to convert a specified object into a human-
Use Case
readable string format.
Syntax str(object, encoding=encoding, errors=errors)
Parameter object (Required) — Any Python object to be converted into a string.
encoding (Optional) — String encoding type. Used only when converting
from bytes.
errors (Optional) — Specifies how to handle encoding errors (e.g.,
'strict', 'ignore', 'replace').
Useful Information
No. Point Description
1 Default Conversion If only an object is passed, it returns its readable string form.
2 Encoding Support encoding is used only when the input is a bytes-like object.
Works with Converts integers, floats, and other numeric types to their
3
Numbers string form.
# Example 1: Converting a float to string
x = str(7.5)
print(x)
# Output: '7.5'
# Example 2: Converting a boolean value to string
status = str(True)
print(status)
# Output: 'True'
# Example 3: Using str() on a list
items = ["AI", "ML", "NLP"]
output = str(items)
print(output)
# Output: "['AI', 'ML', 'NLP']"
# Example 4: Decoding bytes using str()
binary_data = b'Intensity'
decoded = str(binary_data, encoding='utf-8')
print(decoded)
# Output: 'Intensity'
# Explanation: The byte string is decoded to a readable string using UTF-
8 encoding.
7.5
True
['AI', 'ML', 'NLP']
Intensity
62. sum()
Point Description
The sum() function calculates the total of all numeric elements in an
Use Case
iterable.
Syntax sum(iterable, start)
iterable (Required) — A sequence (like list, tuple) containing numeric
Parameter
values to be added.
start (Optional) — A number to be added to the final result. Default is 0.
Useful Information
No. Point Description
Works with Numeric Can be used with lists, tuples, or other iterable
1
Iterables structures containing only numbers.
2 Supports Optional Start Adds the start value to the total sum of elements.
Does Not Accept Non- All elements must be numeric, or a TypeError will be
3
Numeric Types raised.
# Example 1: Basic summation of a tuple
data = (1, 3, 5, 7, 9)
total = sum(data)
print(total)
# Output: 25
# Example 2: Using a starting value in sum
data = (1, 3, 5, 7, 9)
total = sum(data, 10)
print(total)
# Output: 35
# Example 3: Summing a list of floating point values
values = [0.25, 0.30, 0.28, 0.22]
total = sum(values)
print(total)
# Output: 1.05
25
35
1.05
63. super()
Point Description
The super() function is used to access methods and properties of a parent
Use Case
(base) class from within a child (derived) class.
Syntax super()
This function does not require any parameters. It automatically refers to
Parameter
the parent class in the current context.
Useful Information
No. Point Description
Commonly used when child classes inherit and extend
1 Used in Inheritance
functionality from parent classes.
Ensures DRY Helps avoid code duplication by calling parent methods
2
Principles directly.
Supports Multiple Works properly with Python’s method resolution order
3
Inheritance (MRO) in multi-inheritance scenarios.
Mainly Used Inside Often used in constructor overriding (__init__) to ensure
4
__init__ base class initialization is not skipped.
Returns a Proxy The result of super() is a proxy that delegates method
5
Object calls to a parent or sibling class.
# Example: Using super() to reuse parent class initialization logic
class ModelConfig:
def __init__(self, model_name):
self.model_name = model_name
print(f"Base configuration loaded for model: {self.model_name}")
# The MLTrainer class inherits from ModelConfig
class MLTrainer(ModelConfig):
def __init__(self, model_name, epochs):
# Call the parent class's __init__ method using super()
super().__init__(model_name)
[Link] = epochs
print(f"Training initialized for {[Link]} epochs")
# Create an instance of MLTrainer
trainer = MLTrainer("IntensityNet", 10)
# Output:
# Base configuration loaded for model: IntensityNet
# Training initialized for 10 epochs
Base configuration loaded for model: IntensityNet
Training initialized for 10 epochs
64. tuple()
Point Description
The tuple() function is used to create an immutable ordered collection of
Use Case items. Once created, the contents of a tuple cannot be modified (i.e., no
additions, deletions, or updates).
Syntax tuple(iterable)
iterable (Optional) — A sequence (like a list, string, or set) or any iterable
Parameter
object to be converted into a tuple.
Useful Information
No. Point Description
Tuples are fixed in size—once created, their elements
1 Immutable
cannot be changed.
2 Order Preserved Tuples retain the order of the original iterable.
No. Point Description
Can Hold Multiple
3 Supports mixed data types (e.g., int, str, list, etc.).
Types
Tuples consume less memory compared to lists due to
4 Memory Efficient
immutability.
Useful in Function Commonly used to return multiple values from a function
5
Returns or represent fixed groupings.
# Converting a list into a tuple using tuple()
features = ["height", "weight", "age"]
immutable_features = tuple(features)
print("Tuple of features:", immutable_features)
# Output:
# Tuple of features: ('height', 'weight', 'age')
# Using tuple() with a string
chars = tuple("AI")
print("Tuple from string:", chars)
# Output:
# Tuple from string: ('A', 'I')
# Using tuple() with a range object
numbers = tuple(range(3))
print("Tuple from range:", numbers)
# Output:
# Tuple from range: (0, 1, 2)
# Tuple can contain different data types
mixed = tuple([42, "text", 3.14, True])
print("Mixed type tuple:", mixed)
# Output:
# Mixed type tuple: (42, 'text', 3.14, True)
Tuple of features: ('height', 'weight', 'age')
Tuple from string: ('A', 'I')
Tuple from range: (0, 1, 2)
Mixed type tuple: (42, 'text', 3.14, True)
65. type()
Point Description
The type() function is used to determine the data type of an object. It can
Use Case also dynamically create new types (classes) if additional parameters are
provided.
Syntax type(object) or type(name, bases, dict)
object (Required) - If only one argument is passed, returns the type of the
Parameters
object.
name (Required if using 3-arg form) - The name of the new class to be
created.
bases (Optional) - A tuple specifying the base classes (inheritance).
dict (Optional) - A dictionary defining the attributes and methods of the
class.
Useful Information
No. Point Description
Commonly Used for Helps during debugging, logging, or validating input
1
Type-Checking types in functions.
Supports One or Three With one argument, it returns the type. With three, it
2
Arguments dynamically creates a new class.
Using three arguments returns <class 'type'> for
3 Creates Dynamic Types
dynamically created types.
# Example 1: Type Checking
features = ('height', 'weight', 'age')
print("Type of features:", type(features))
# Output: <class 'tuple'>
# Check the type of a label (string)
label = "healthy"
print("Type of label:", type(label))
# Output: <class 'str'>
# Check the type of a value (integer)
value = 95
print("Type of value:", type(value))
# Output: <class 'int'>
Type of features: <class 'tuple'>
Type of label: <class 'str'>
Type of value: <class 'int'>
# Example 2: Dynamically Creating a Class Using type()
# Create a simple class dynamically using type()
# Equivalent to:
# class Model:
# version = 1.0
Model = type('Model', (), {'version': 1.0})
# Create an instance
ml_model = Model()
print("Model version:", ml_model.version)
# Output: Model version: 1.0
Model version: 1.0
66. vars()
Point Description
The vars() function is used to retrieve the __dict__ attribute of an object,
Use Case
which holds its writable attributes in the form of a dictionary.
Syntax vars(object)
object (Optional) — An object that has a __dict__ attribute. If omitted, it
Parameter
returns the local symbol table as a dictionary.
Useful Information
No. Point Description
Requires __dict__ Only works on objects that define a __dict__ attribute
1
Support (like user-defined classes).
Commonly used to inspect and debug the current state
2 Used for Introspection
of an object's attributes.
Local Namespace (No When no argument is provided, vars() returns the
3
Argument) local variable scope as a dictionary.
Will raise a TypeError if called on a built-in type that
4 Not for Built-in Types
doesn’t support __dict__.
# Define a user-defined class
class Developer:
role = "ML Engineer"
experience = 5
team = "Intensity Coding"
# Use vars() to inspect the attributes of the class
dev_attributes = vars(Developer)
# Print the dictionary of attributes
print(dev_attributes)
# Output: {'role': 'ML Engineer', 'experience': 5, 'team': 'Intensity
Coding'}
{'__module__': '__main__', 'role': 'ML Engineer', 'experience': 5,
'team': 'Intensity Coding', '__dict__': <attribute '__dict__' of
'Developer' objects>, '__weakref__': <attribute '__weakref__' of
'Developer' objects>, '__doc__': None}
# Using vars() without arguments to check local scope
language = "Python"
level = "Advanced"
local_vars = vars()
print(local_vars)
# Output will include keys like 'language' and 'level' with their values
67. zip()
Point Description
The zip() function combines elements from multiple iterables (e.g., lists,
Use Case
tuples) into tuples, grouping items based on their positions.
Syntax zip(iterator1, iterator2, ...)
iterator1, iterator2, ... (Required) — Two or more iterable objects to
Parameter
be zipped together.
Useful Information
No. Point Description
If the input iterables are of unequal length, the resulting
1 Shortest Length Wins
iterator stops at the shortest.
Returns a zip object which is an iterator — convert it to
2 Produces an Iterator
list or tuple to view results.
Supports More than You can pass more than two iterables to group multiple
3
Two Inputs sets together.
Since it returns an iterator, it uses memory efficiently
4 Lazy Evaluation
and supports large datasets.
# Example 1: Zipping two tuples of equal length
names = ("Alice", "Bob", "Charlie")
roles = ("Data Scientist", "ML Engineer", "Researcher")
paired = zip(names, roles)
# Convert the zip object to a tuple to see the result
print(tuple(paired))
# Output: (('Alice', 'Data Scientist'), ('Bob', 'ML Engineer'),
('Charlie', 'Researcher'))
(('Alice', 'Data Scientist'), ('Bob', 'ML Engineer'), ('Charlie',
'Researcher'))
# Example 2: Zipping tuples of unequal lengths
contributors = ("Raj", "Anita", "Sanjay")
teams = ("NLP", "Computer Vision")
zipped_output = zip(contributors, teams)
print(tuple(zipped_output))
# Output: (('Raj', 'NLP'), ('Anita', 'Computer Vision'))
# Explanation: Stops after the shortest iterable (`teams`) ends
(('Raj', 'NLP'), ('Anita', 'Computer Vision'))
# Example 3: Zipping three lists together
tech = ["Python", "TensorFlow", "PyTorch"]
years = [1991, 2015, 2016]
use_case = ["General Purpose", "Deep Learning", "Research DL"]
zipped_info = zip(tech, years, use_case)
print(list(zipped_info))
# Output: [('Python', 1991, 'General Purpose'), ('TensorFlow', 2015,
'Deep Learning'), ('PyTorch', 2016, 'Research DL')]
[('Python', 1991, 'General Purpose'), ('TensorFlow', 2015, 'Deep
Learning'), ('PyTorch', 2016, 'Research DL')]
[Link]
Found this helpful ?
Follow on LinkedIn
Master AI/ML with Intensity Coding
Bhavdip Patel
@bhavdippatel2020
Like Comment Share Save
Each Article 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
Explore more tutorials at Intensity Coding
[Link]