Python Built -In Functions

String Methods Examples

Problem: How to remove whitespaces from a string?

Solution: strip():
Description: "Removes whitespaces from the start and end."

s = ' hello '.strip()

Example 1: s = ' hello '.strip()
Output: 'hello'

Example 2: s = ' python '.strip()
Output: 'python'

Problem: How to split a string into a list?

Solution: split():
Description: "Splits a string into a list."

words = 'one,two,three'.split(',')

Example 1: words = 'one,two,three'.split(',')
Output: ['one', 'two', 'three']

Example 2: words = 'apple orange banana'.split(' ')
Output: ['apple', 'orange', 'banana']

Problem: How to join elements of an iterable?

Solution: join():
Description: "Joins elements of an iterable."

s = '-'.join(['one', 'two', 'three'])

Example 1: s = '-'.join(['one', 'two', 'three'])
Output: 'one-two-three'

Example 2: s = '+'.join(['apple', 'orange', 'banana'])
Output: 'apple+orange+banana'

Problem: How to replace substrings in a string?

Solution: replace():
Description: "Replaces substrings."

s = 'hello'.replace('l', 'r')

Example 1: s = 'hello'.replace('l', 'r')
Output: 'herro'

Example 2: s = 'programming'.replace('gram', 'python')
Output: 'pythonming'

Problem: How to convert a string to uppercase?

Solution: upper():
Description: "Converts to uppercase."

s = 'hello'.upper()

Example 1: s = 'hello'.upper()
Output: 'HELLO'

Example 2: s = 'python'.upper()
Output: 'PYTHON'

Problem: How to convert a string to lowercase?

Solution: lower():
Description: "Converts to lowercase."

s = 'Hello'.lower()

Example 1: s = 'Hello'.lower()
Output: 'hello'

Example 2: s = 'PYTHON'.lower()
Output: 'python'

Problem: How to capitalize the first character of a string?

Solution: capitalize():
Description: "Converts the first character of a string to uppercase."

s = 'hello world'
result = s.capitalize()

Example: s = 'hello world'.capitalize()
Output: 'Hello world'

Problem: How to title case a string?

Solution: title():
Description: "Converts the first character of each word to uppercase."

s = 'python programming'
result = s.title()

Example: s = 'python programming'.title()
Output: 'Python Programming'

Problem: How to check if a string starts with a specific prefix?

Solution: startswith():
Description: "Checks prefix."

b = s.startswith('He')

Example 1: b = 'Hello'.startswith('He')
Output: True

Example 2: b = 'Python'.startswith('Py')
Output: True

Problem: How to check if a string ends with a specific suffix?

Solution: endswith():
Description: "Checks suffix."

b = s.endswith('lo')

Example 1: b = 'Hello'.endswith('lo')
Output: True

Example 2: b = 'Python'.endswith('on')
Output: True

Problem: How to find the index of a substring in a string?

Solution: find():
Description: "Finds substring index."

idx = s.find('l')

Example 1: idx = 'hello'.find('l')
Output: 2

Example 2: idx = 'programming'.find('gram')
Output: 3

Problem: How to check if all characters in a string are digits?

Solution: isdigit():
Description: "Checks if all characters are digits."

b = '123'.isdigit()

Example 1: b = '123'.isdigit()
Output: True

Example 2: b = '42'.isdigit()
Output: True

Problem: How to check if all characters in a string are alphabetic?

Solution: isalpha():
Description: "Checks if all characters are alphabetic."

b = 'abc'.isalpha()

Example 1: b = 'abc'.isalpha()
Output: True

Example 2: b = 'Python'.isalpha()
Output: True

List Methods Examples

Problem: How to add an element to a list?

Solution: append():
Description: "Adds an element."

lst.append('new')

Example 1: lst.append('new')
List: [1, 2, 3, 'new']

Example 2: lst.append(42)
List: [1, 2, 3, 'new', 42]

Problem: How to append iterable elements to a list?

Solution: extend():
Description: "Appends iterable elements."

lst.extend([4, 5])

Example 1: lst.extend([4, 5])
List: [1, 2, 3, 'new', 42, 4, 5]

Example 2: lst.extend(['a', 'b'])
List: [1, 2, 3, 'new', 42, 4, 5, 'a', 'b']

Problem: How to insert an element at a specific index in a list?

Solution: insert():
Description: "Inserts at index."

lst.insert(1, 'inserted')

Example 1: lst.insert(1, 'inserted')
List: [1, 'inserted', 2, 3, 'new', 42, 4, 5, 'a', 'b']

Example 2: lst.insert(0, 'start')
List: ['start', 1, 'inserted', 2, 3, 'new', 42, 4, 5, 'a', 'b']

Problem: How to remove the first occurrence of an element from a list?

Solution: remove():
Description: "Removes first occurrence."

lst.remove('item')

Example 1: lst.remove('new')
List: [1, 'inserted', 2, 3, 42, 4, 5, 'a', 'b']

Example 2: lst.remove(3)
List: [1, 'inserted', 2, 42, 4, 5, 'a', 'b']

Problem: How to remove and return an element from a specific index in a list?

Solution: pop():
Description: "Removes and returns an element."

item = lst.pop()

Example 1: item = lst.pop()
List: [1, 'inserted', 2, 42, 4, 5, 'a'], Item: 'b'

Example 2: item = lst.pop(2)
List: [1, 'inserted', 42, 4, 5, 'a'], Item: 2

Problem: How to find the first index of a value in a list?

Solution: index():
Description: "Returns the first index of value."

idx = lst.index('item')

Example 1: idx = lst.index('inserted')
Index: 1

Example 2: idx = lst.index(42)
Index: 2

Problem: How to count occurrences of an element in a list?

Solution: count():
Description: "Counts occurrences."

cnt = lst.count('item')

Example 1: cnt = lst.count('inserted')
Count: 1

Example 2: cnt = lst.count(42)
Count: 1

Problem: How to sort a list?

Solution: sort():
Description: "Sorts the list."

lst.sort()

Example 1: lst.sort()
Sorted List: [1, 2, 4, 5, 'a', 'inserted']

Example 2: lst.sort(reverse=True)
Reverse Sorted List: ['inserted', 'a', 5, 4, 2, 1]

Problem: How to reverse a list?

Solution: reverse():
Description: "Reverses the list."

lst.reverse()

Example 1: lst.reverse()
Reversed List: ['inserted', 'a', 5, 4, 2, 1]

Example 2: lst.reverse() (again)
Reversed List: [1, 2, 4, 5, 'a', 'inserted']

Problem: How to create a shallow copy of a list?

Solution: copy():
Description: "Returns a shallow copy of the list."

original_list = [1, 2, 3]
copied_list = original_list.copy()

Example: original_list = [1, 2, 3] copied_list = original_list.copy()
Copied List: [1, 2, 3]

Problem: How to remove all elements from a list?

Solution: clear():
Description: "Removes all elements from the list."

lst = [4, 5, 6]
lst.clear()

Example: lst = [4, 5, 6] lst.clear()
Empty List: []

Dictionary Methods Examples

Problem: How to retrieve a value for a key in a dictionary?

Solution: get():
Description: "Retrieves value for key."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
value = my_dict.get('name')

Example 1: value = my_dict.get('name')
Value: 'John'

Example 2: value = my_dict.get('age')
Value: 25

Problem: How to get the keys from a dictionary?

Solution: keys():
Description: "Returns dictionary keys."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
keys = my_dict.keys()

Example 1: keys = my_dict.keys()
Keys: ['name', 'age', 'city']

Example 2: keys = my_dict.keys() (after modifying dictionary)
Keys: ['name', 'age', 'city', 'country']

Problem: How to get the values from a dictionary?

Solution: values():
Description: "Returns dictionary values."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
values = my_dict.values()

Example 1: values = my_dict.values()
Values: ['John', 25, 'New York']

Example 2: values = my_dict.values() (after modifying dictionary)
Values: ['John', 25, 'New York', 'USA']

Problem: How to get key-value pairs from a dictionary?

Solution: items():
Description: "Returns key-value pairs."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
items = my_dict.items()

Example 1: items = my_dict.items()
Items: [('name', 'John'), ('age', 25), ('city', 'New York')]

Example 2: items = my_dict.items() (after modifying dictionary)
Items: [('name', 'John'), ('age', 25), ('city', 'New York'), ('country', 'USA')]

Problem: How to update a dictionary with new key-value pairs?

Solution: update():
Description: "Updates dictionary."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
my_dict.update({'new_key': 'new_value'})

Example 1: my_dict.update({'age': 26})
Updated Dictionary: {'name': 'John', 'age': 26, 'city': 'New York'}

Example 2: my_dict.update({'country': 'USA'})
Updated Dictionary: {'name': 'John', 'age': 26, 'city': 'New York', 'country': 'USA'}

Problem: How to remove a key and return its value from a dictionary?

Solution: pop():
Description: "Removes key and returns value."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
value = my_dict.pop('age')

Example 1: value = my_dict.pop('age')
Value: 26

Example 2: value = my_dict.pop('country', 'Default')
Value: 'USA' (if 'country' exists), 'Default' (if 'country' doesn't exist)

Problem: How to remove the last inserted key-value pair from a dictionary?

Solution: popitem():
Description: "Removes last inserted key-value pair."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
item = my_dict.popitem()

Example 1: item = my_dict.popitem()
Item: ('country', 'USA')

Example 2: item = my_dict.popitem() (after modifying dictionary)
Item: ('city', 'New York')

Problem: How to clear all elements from a dictionary?

Solution: clear():
Description: "Clears the dictionary."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
my_dict.clear()

Example 1: my_dict.clear()
Cleared Dictionary: {}

Example 2: my_dict.clear() (after modifying dictionary)
Cleared Dictionary: {}

Problem: How to retrieve a value for a key or insert a default value if the key does not exist?

Solution: setdefault():
Description: "Returns the value of the specified key. If the key does not exist, insert the key with a specified value."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
value = my_dict.setdefault('new_key', 'default_value')

Example 1: value = my_dict.setdefault('new_key', 'default_value')
Value: 'default_value'

Example 2: value = my_dict.setdefault('age', 30)
Value: 26 (since 'age' key already exists)

Problem: How to create a new dictionary with keys from a sequence and values set to a specified value?

Solution: fromkeys():
Description: "Creates a new dictionary with keys from a sequence and values set to a specified value."

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
keys = ['a', 'b', 'c']
default_value = 0
new_dict = dict.fromkeys(keys, default_value)

Example 1: keys = ['a', 'b', 'c'] default_value = 0 new_dict = dict.fromkeys(keys, default_value)
New Dictionary: {'a': 0, 'b': 0, 'c': 0}

Example 2: keys = ['x', 'y', 'z'] default_value = 'default' new_dict = dict.fromkeys(keys, default_value)
New Dictionary: {'x': 'default', 'y': 'default', 'z': 'default'}

Set Methods Examples

Problem: How to add an element to a set?

Solution: add():
Description: "Adds an element."

st1 = {1, 2, 3}
st1.add(4)

Example 1: st1.add(4)
Updated Set 1: {1, 2, 3, 4}

Example 2: st1.add(5)
Updated Set 1: {1, 2, 3, 4, 5}

Problem: How to remove an element from a set?

Solution: remove():
Description: "Removes an element."

st1 = {1, 2, 3}
st1.remove(3)

Example 1: st1.remove(3)
Updated Set 1: {1, 2, 4, 5}

Example 2: st1.remove(5)
Updated Set 1: {1, 2, 4}

Problem: How to remove an element from a set if present?

Solution: discard():
Description: "Removes an element if present."

st1 = {1, 2, 3}
st1.discard(2)

Example 1: st1.discard(2)
Updated Set 1: {1, 4}

Example 2: st1.discard(5) (element not present)
Set 1 remains unchanged: {1, 4}

Problem: How to remove and return an element from a set?

Solution: pop():
Description: "Removes and returns an element."

st1 = {1, 2, 3}
item = st1.pop()

Example 1: item = st1.pop()
Removed Item: 1, Updated Set 1: {4}

Example 2: item = st1.pop()
Removed Item: 4, Updated Set 1: {}

Problem: How to remove all elements from a set?

Solution: clear():
Description: "Removes all elements."

st1 = {1, 2, 3}
st1.clear()

Example 1: st1.clear()
Cleared Set 1: {}

Example 2: st2.clear() (clearing another set)
Cleared Set 2: {}

Problem: How to get the union of two sets?

Solution: union():
Description: "Returns the union of sets."

st1 = {1, 2, 3}
st2 = {2, 3, 4}
union_set = st1.union(st2)

Example 1: union_set = st1.union(st2)
Union Set: {2, 3, 4}

Example 2: union_set = st1.union({4, 5, 6})
Union Set: {2, 3, 4, 5, 6}

Problem: How to get the intersection of two sets?

Solution: intersection():
Description: "Returns the intersection."

st1 = {1, 2, 3}
st2 = {2, 3, 4}
intersect_set = st1.intersection(st2)

Example 1: intersect_set = st1.intersection(st2)
Intersection Set: {2}

Example 2: intersect_set = st1.intersection({1, 2, 3, 4})
Intersection Set: {}

Problem: How to get the difference of two sets?

Solution: difference():
Description: "Returns the difference."

st1 = {1, 2, 3}
st2 = {2, 3, 4}
difference_set = st1.difference(st2)

Example 1: difference_set = st1.difference(st2)
Difference Set: {1}

Example 2: difference_set = st1.difference({2, 3})
Difference Set: {1}

File I/O Methods Examples

Problem: How to open a file in read mode?

Solution: open():
Description: "Opens a file."

file = open('file.txt', 'r')

Example 1: file = open('example.txt', 'r')
Opened File: example.txt

Example 2: file = open('data.csv', 'r')
Opened File: data.csv

Problem: How to read the entire content of a file?

Solution: read():
Description: "Reads the entire file."

content = file.read()

Example 1: content = file.read() (after opening 'example.txt')
Content: 'Hello, World!\nThis is an example.'

Example 2: content = file.read() (after opening 'data.csv')
Content: 'Name, Age, City\nJohn, 25, New York\nJane, 30, Los Angeles'

Problem: How to read one line from a file?

Solution: readline():
Description: "Reads one line."

line = file.readline()

Example 1: line = file.readline() (after opening 'example.txt')
Line: 'Hello, World!'

Example 2: line = file.readline() (after opening 'data.csv')
Line: 'Name, Age, City\n'

Problem: How to read lines from a file into a list?

Solution: readlines():
Description: "Reads lines into a list."

lines = file.readlines()

Example 1: lines = file.readlines() (after opening 'example.txt')
Lines: ['Hello, World!\n', 'This is an example.']

Example 2: lines = file.readlines() (after opening 'data.csv')
Lines: ['Name, Age, City\n', 'John, 25, New York\n', 'Jane, 30, Los Angeles']

Problem: How to write a string to a file?

Solution: write():
Description: "Writes a string."

file.write('hello')

Example 1: file.write('hello') (after opening 'example.txt')
File Content: 'hello, World!\nThis is an example.'

Example 2: file.write('Python') (after opening 'data.csv')
File Content: 'Name, Age, City\nJohn, 25, New York\nJane, 30, Los AngelesPython'

Problem: How to write a list of strings to a file?

Solution: writelines():
Description: "Writes a list of strings."

file.writelines(['hello\n', 'world'])

Example 1: file.writelines(['hello\n', 'world']) (after opening 'example.txt')
File Content: 'hello, World!\nThis is an example.helloworld'

Example 2: file.writelines(['apple\n', 'orange\n', 'banana']) (after opening 'data.csv')
File Content: 'Name, Age, City\nJohn, 25, New York\nJane, 30, Los AngelesPythonapple\norange\nbanana'

Problem: How to close a file?

Solution: close():
Description: "Closes the file."

file.close()

Example 1: file.close() (after writing to 'example.txt')

Example 2: file.close() (after writing to 'data.csv')

Problem: How to move the file cursor and get its current position?

Solution: seek() and tell()
Description: "Seek sets the file's current position. Tell returns the current position."

            file.seek(offset, whence)
            position = file.tell()
        

Example 1: file.seek(0) (move to the beginning)

Example 2: position = file.tell() (get current position)

General Purpose Function Examples

Problem: How to get the length of an iterable?

Solution: len():
Description: "Returns the length."

length = len(iterable)

Example 1: length = len('hello')
Length: 5

Example 2: length = len([1, 2, 3, 4, 5])
Length: 5

Problem: How to generate a range of numbers?

Solution: range():
Description: "Generates a range of numbers."

for i in range(10):

Example 1: for i in range(5)
Values: 0, 1, 2, 3, 4

Example 2: for i in range(2, 10, 2)
Values: 2, 4, 6, 8

Problem: How to print to the console?

Solution: print():
Description: "Prints to the console."

print('Hello, world!')

Example 1: print('Hello, world!')
Output: Hello, world!

Example 2: print('Python is awesome!')
Output: Python is awesome!

Problem: How to get the type of an object?

Solution: type():
Description: "Returns the type."

t = type(obj)

Example 1: t = type(42)
Type: int

Example 2: t = type('hello')
Type: str

Problem: How to get the unique identifier of an object?

Solution: id():
Description: "Returns the unique identifier."

identifier = id(obj)

Example 1: identifier = id([1, 2, 3])
Identifier: 140244774556416

Example 2: identifier = id('hello')
Identifier: 140244774579168

Problem: How to get a sorted list from an iterable?

Solution: sorted():
Description: "Returns a sorted list."

sorted_lst = sorted(iterable)

Example 1: sorted_lst = sorted([3, 1, 4, 1, 5, 9, 2])
Sorted List: [1, 1, 2, 3, 4, 5, 9]

Example 2: sorted_lst = sorted('python')
Sorted List: ['h', 'n', 'o', 'p', 't', 'y']

Problem: How to add a counter to an iterable?

Solution: enumerate():
Description: "Adds a counter to an iterable."

for index, value in enumerate(lst):

Example 1: for index, value in enumerate(['apple', 'banana', 'orange'])
Index-Value Pairs: (0, 'apple'), (1, 'banana'), (2, 'orange')

Example 2: for index, value in enumerate('python', start=1)
Index-Value Pairs: (1, 'p'), (2, 'y'), (3, 't'), (4, 'h'), (5, 'o'), (6, 'n')

Problem: How to aggregate elements from iterables?

Solution: zip():
Description: "Aggregates elements from iterables."

for a, b in zip(lst1, lst2):

Example 1: for a, b in zip([1, 2, 3], ['a', 'b', 'c'])
Pairs: (1, 'a'), (2, 'b'), (3, 'c')

Example 2: for a, b in zip('abc', '123')
Pairs: ('a', '1'), ('b', '2'), ('c', '3')

Conversion Functions Examples

Problem: How to convert a string to an integer?

Solution: int():
Description: "Converts to an integer."

i = int('123')

Example 1: i = int('123')
Value: 123

Example 2: i = int('-45')
Value: -45

Problem: How to convert a string to a float?

Solution: float():
Description: "Converts to a float."

f = float('123.45')

Example 1: f = float('123.45')
Value: 123.45

Example 2: f = float('-67.89')
Value: -67.89

Problem: How to convert a number to a string?

Solution: str():
Description: "Converts to a string."

s = str(123)

Example 1: s = str(123)
Value: '123'

Example 2: s = str(-45.67)
Value: '-45.67'

Problem: How to convert a string to a list of characters?

Solution: list():
Description: "Converts to a list."

lst = list('abc')

Example 1: lst = list('abc')
List: ['a', 'b', 'c']

Example 2: lst = list('hello')
List: ['h', 'e', 'l', 'l', 'o']

Problem: How to convert a list of key-value pairs to a dictionary?

Solution: dict():
Description: "Converts to a dictionary."

dct = dict([(1, 'one'), (2, 'two')])

Example 1: dct = dict([(1, 'one'), (2, 'two')])
Dictionary: {1: 'one', 2: 'two'}

Example 2: dct = dict([(3, 'three'), (4, 'four')])
Dictionary: {3: 'three', 4: 'four'}

Problem: How to convert a list to a set?

Solution: set():
Description: "Converts to a set."

st = set([1, 2, 3])

Example 1: st = set([1, 2, 3])
Set: {1, 2, 3}

Example 2: st = set([3, 4, 5])
Set: {3, 4, 5}

Problem: How to convert a list to a tuple?

Solution: tuple():
Description: "Converts to a tuple."

t = tuple([1, 2, 3])

Example 1: t = tuple([1, 2, 3])
Tuple: (1, 2, 3)

Example 2: t = tuple([4, 5, 6])
Tuple: (4, 5, 6)

Problem: How to convert a value to a boolean?

Solution: bool():
Description: "Converts to a boolean."

is_true = bool(1)

Example 1: is_true = bool(1)
Value: True

Example 2: is_true = bool('hello')
Value: True

Problem: How to convert an ASCII value to its corresponding character?

Solution: chr():
Description: "Converts an ASCII value to its corresponding character."

character = chr(65)

Example 1: character = chr(65)
Character: 'A'

Example 2: character = chr(97)
Character: 'a'

Mathematical Functions Examples

Problem: How to get the absolute value of a number?

Solution: abs():
Description: "Returns the absolute value."

absolute = abs(-5)

Example 1: absolute = abs(-5)
Absolute Value: 5

Example 2: absolute = abs(3.14)
Absolute Value: 3.14

Problem: How to sum a list of numbers?

Solution: sum():
Description: "Sums the items."

total = sum([1, 2, 3])

Example 1: total = sum([1, 2, 3])
Sum: 6

Example 2: total = sum([4, 5, 6])
Sum: 15

Problem: How to find the minimum value in a list?

Solution: min():
Description: "Returns the minimum."

minimum = min([1, 2, 3])

Example 1: minimum = min([1, 2, 3])
Minimum Value: 1

Example 2: minimum = min([5, 2, 8])
Minimum Value: 2

Problem: How to find the maximum value in a list?

Solution: max():
Description: "Returns the maximum."

maximum = max([1, 2, 3])

Example 1: maximum = max([1, 2, 3])
Maximum Value: 3

Example 2: maximum = max([5, 2, 8])
Maximum Value: 8

Problem: How to raise a number to a power?

Solution: pow():
Description: "Raises a number to a power."

result = pow(2, 3)

Example 1: result = pow(2, 3)
Result: 8

Example 2: result = pow(5, 2)
Result: 25

Problem: How to round a decimal number?

Solution: round():
Description: "Rounds a number."

rounded = round(3.14)

Example 1: rounded = round(3.14)
Rounded Value: 3

Example 2: rounded = round(2.75)
Rounded Value: 3

Problem: How to find the square root of a number?

Solution: sqrt():
Description: "Returns the square root."

square_root = sqrt(25)

Example 1: square_root = sqrt(25)
Square Root: 5.0

Example 2: square_root = sqrt(9)
Square Root: 3.0

Problem: How to calculate the factorial of a number?

Solution: factorial():
Description: "Returns the factorial."

fact_result = factorial(4)

Example 1: fact_result = factorial(4)
Factorial: 24

Example 2: fact_result = factorial(5)
Factorial: 120

Functional Programming Tools Examples

Problem: How to filter elements?

Solution: filter():
Description: "Filters elements."

evens = filter(lambda x: x % 2 == 0, lst)

Example 1: evens = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])
Filtered Evens: [2, 4]

Example 2: evens = filter(lambda x: x % 2 == 0, [6, 7, 8, 9, 10])
Filtered Evens: [6, 8, 10]

Problem: How to apply a function to elements?

Solution: map():
Description: "Applies a function."

squares = map(lambda x: x**2, lst)

Example 1: squares = map(lambda x: x**2, [1, 2, 3, 4, 5])
Squared Values: [1, 4, 9, 16, 25]

Example 2: squares = map(lambda x: x**2, [6, 7, 8, 9, 10])
Squared Values: [36, 49, 64, 81, 100]

Problem: How to reduce elements to a single value?

Solution: reduce():
Description: "Reduces to a single value."

from functools import reduce; total = reduce(lambda a, b: a + b, lst)

Example 1: from functools import reduce; total = reduce(lambda a, b: a + b, [1, 2, 3, 4, 5])
Total Sum: 15

Example 2: from functools import reduce; total = reduce(lambda a, b: a + b, [6, 7, 8, 9, 10])
Total Sum: 40

Input and Output Examples

Problem: How to read a string from input?

Solution: input():
Description: "Reads a string from input."

s = input('Enter something: ')

Example 1: s = input('Enter something: ')
Entered String: (user input)

Example 2: s = input('Enter a number: ')
Entered String: (user input)

Problem: How to format a string?

Solution: format():
Description: "Formats a string."

formatted = format(123.4567, '.2f')

Example 1: formatted = format(123.4567, '.2f')
Formatted String: '123.46'

Example 2: formatted = format(987.6543, '.3f')
Formatted String: '987.654'

Miscellaneous Examples

Problem: How to get the global symbol table?

Solution: globals():
Description: "Returns the global symbol table."

global_symbols = globals()

Example 1: global_symbols = globals()
Global Symbols: (dictionary)

Example 2: global_symbols['variable'] = 42
Updated Global Symbols: (dictionary)

Problem: How to get the local symbol table?

Solution: locals():
Description: "Returns the local symbol table."

local_symbols = locals()

Example 1: local_symbols = locals()
Local Symbols: (dictionary)

Example 2: local_symbols['variable'] = 42
Updated Local Symbols: (dictionary)

Problem: How to check if an object is callable?

Solution: callable():
Description: "Checks if an object is callable."

is_callable = callable(obj)

Example 1: is_callable = callable(print)
Is Callable: True

Example 2: is_callable = callable(42)
Is Callable: False

Problem: How to evaluate a Python expression?

Solution: eval():
Description: "Evaluates a Python expression."

result = eval('1 + 2')

Example 1: result = eval('1 + 2')
Result: 3

Example 2: result = eval('3 * 4')
Result: 12

Problem: How to execute Python code dynamically?

Solution: exec():
Description: "Executes Python code dynamically."

exec('print(42)')

Example 1: exec('print("Hello, World!")')
Output: Hello, World!

Example 2: exec('result = 2 + 2')
Result: 4

Exception Handling Examples

Problem: How to handle exceptions?

Solution: try/except/finally:
Description: "Handles exceptions."

try: risky_operation() except Exception as e: handle_exception() finally: cleanup()

Example 1: try: risky_operation() except ValueError as e: handle_exception()
Exception Handled

Example 2: try: risky_operation() finally: cleanup()
Cleanup Executed

Problem: How to delete an object?

Solution: del():
Description: "Deletes an object."

del obj

Example 1: del obj
Object Deleted: obj no longer exists

Example 2: del my_list[2]
Item Deleted: my_list[2]

Problem: How to force garbage collection?

Solution: gc.collect():
Description: "Forces garbage collection."

import gc; gc.collect()

Example 1: import gc; gc.collect()
Garbage Collection Forced

Example 2: gc.collect()
Garbage Collection Forced

Working with Iterables Examples

Problem: How to retrieve the next item from an iterator?

Solution: next():
Description: "Retrieves the next item from an iterator."

item = next(iterator)

Example 1: item = next(iter([1, 2, 3]))
Next Item: 1

Example 2: item = next(iter(['a', 'b', 'c']))
Next Item: 'a'

Problem: How to get an iterator from an iterable?

Solution: iter():
Description: "Returns an iterator."

iterator = iter(iterable)

Example 1: iterator = iter([1, 2, 3])
Iterator Created

Example 2: iterator = iter(('x', 'y', 'z'))
Iterator Created

Decorators and Metaprogramming Examples

Problem: How to convert a method to a static method?

Solution: staticmethod():
Description: "Converts a method to a static method."

@staticmethod def func():

Example 1: @staticmethod def func():
Static Method Created

Example 2: @staticmethod def calculate():
Static Method Created

Problem: How to convert a method to a class method?

Solution: classmethod():
Description: "Converts a method to a class method."

@classmethod def func(cls):

Example 1: @classmethod def func(cls):
Class Method Created

Example 2: @classmethod def initialize(cls):
Class Method Created

Context Managers Examples

Problem: How to manage resources with context?

Solution: with/as:
Description: "Manages resource with context."

with open('file.txt') as file:

Example 1: with open('file.txt') as file:
File Opened

Example 2: with database_connection() as connection:
Database Connection Established

Comprehensions Examples

Problem: How to create a new list using List Comprehension?

Solution: List Comprehension:
Description: "Creates a new list."

[x * x for x in range(10)]

Example 1: [x * x for x in range(10)]
New List: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Example 2: [2 * x for x in range(5)]
New List: [0, 2, 4, 6, 8]

Problem: How to create a new dictionary using Dict Comprehension?

Solution: Dict Comprehension:
Description: "Creates a new dictionary."

{k: v for k, v in zip(keys, values)}

Example 1: {k: v for k, v in zip(['a', 'b', 'c'], [1, 2, 3])}
New Dictionary: {'a': 1, 'b': 2, 'c': 3}

Example 2: {str(x): x**2 for x in range(3)}
New Dictionary: {'0': 0, '1': 1, '2': 4}

Problem: How to create a new set using Set Comprehension?

Solution: Set Comprehension:
Description: "Creates a new set."

{x for x in iterable if x > 0}

Example 1: {x for x in [1, -2, 3, -4, 5] if x > 0}
New Set: {1, 3, 5}

Example 2: {len(word) for word in ['apple', 'banana', 'cherry']}
New Set: {5, 6}

Problem: How to generate items on-the-fly using Generator Expression?

Solution: Generator Expression:
Description: "Generates items on-the-fly."

(x * x for x in range(10))

Example 1: (x * x for x in range(10))
Generated Items: (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)

Example 2: (2 * x for x in range(5))
Generated Items: (0, 2, 4, 6, 8)

Advanced Python Features Examples

Problem: How to create an anonymous function?

Solution: lambda:
Description: "Creates an anonymous function."

f = lambda x: x * x

Example 1: f = lambda x: x * x
Result: f(3) = 9

Example 2: f = lambda x: x + 5
Result: f(2) = 7

Problem: How to access global variables?

Solution: globals():
Description: "Accesses global variables."

global_vars = globals()

Example 1: global_vars = globals()
Global Variables: {...}

Example 2: global_vars['my_var'] = 42
Global Variables Updated: {'my_var': 42, ...}

Problem: How to access local variables?

Solution: locals():
Description: "Accesses local variables."

local_vars = locals()

Example 1: local_vars = locals()
Local Variables: {...}

Example 2: local_vars['my_var'] = 24
Local Variables Updated: {'my_var': 24, ...}

Problem: How to list properties and methods?

Solution: dir():
Description: "Lists properties and methods."

properties = dir(obj)

Example 1: properties = dir(obj)
Properties and Methods: [..., 'method', 'property', ...]

Example 2: properties = dir(str)
Properties and Methods: [..., 'upper', 'lower', ...]

Serialization Examples

Problem: How to serialize an object?

Solution: pickle.dump():
Description: "Serializes an object."

import pickle; pickle.dump(obj, file)

Example 1: import pickle; pickle.dump({'name': 'John'}, file)
Serialized Object

Example 2: import pickle; pickle.dump([1, 2, 3], file)
Serialized Object

Problem: How to deserialize data?

Solution: pickle.load():
Description: "Deserializes data."

obj = pickle.load(file)

Example 1: obj = pickle.load(file)
Deserialized Object

Example 2: obj = pickle.load(file)
Deserialized Object

Python Runtime Services Examples

Problem: How to execute Python code dynamically?

Solution: exec():
Description: "Executes Python code dynamically."

exec('print("Hello")')

Example 1: exec('print("Hello")')
Dynamic Execution: Hello

Example 2: exec('for i in range(5): print(i)')
Dynamic Execution

Problem: How to evaluate a Python expression?

Solution: eval():
Description: "Evaluates a Python expression."

result = eval('2 + 3')

Example 1: result = eval('2 + 3')
Evaluation Result: 5

Example 2: result = eval('len([1, 2, 3])')
Evaluation Result: 3

Python Attribute and Method Resolution Examples

Problem: How to retrieve an attribute's value?

Solution: getattr():
Description: "Retrieves an attribute's value."

value = getattr(obj, 'attribute')

Example 1: value = getattr(obj, 'name')
Attribute Value: (value)

Example 2: value = getattr(obj, 'age')
Attribute Value: (value)

Problem: How to set an attribute's value?

Solution: setattr():
Description: "Sets an attribute's value."

setattr(obj, 'attribute', value)

Example 1: setattr(obj, 'age', 30)
Attribute Value Set: obj.age = 30

Example 2: setattr(obj, 'name', 'John')
Attribute Value Set: obj.name = 'John'

Problem: How to check if an attribute exists?

Solution: hasattr():
Description: "Checks if an attribute exists."

exists = hasattr(obj, 'attribute')

Example 1: exists = hasattr(obj, 'age')
Attribute Exists: True

Example 2: exists = hasattr(obj, 'address')
Attribute Exists: False

Problem: How to delete an attribute?

Solution: delattr():
Description: "Deletes an attribute."

delattr(obj, 'attribute')

Example 1: delattr(obj, 'age')
Attribute Deleted: obj.age no longer exists

Example 2: delattr(obj, 'name')
Attribute Deleted: obj.name no longer exists

Class and Instance Utilities Examples

Problem: How to check if an object is an instance of a class?

Solution: isinstance():
Description: "Checks if an object is an instance of a class."

if isinstance(obj, MyClass):

Example 1: if isinstance(obj, str):
Object is a String Instance

Example 2: if isinstance(obj, int):
Object is an Integer Instance

Problem: How to check if a class is a subclass of another?

Solution: issubclass():
Description: "Checks if a class is a subclass of another."

if issubclass(MyClass, ParentClass):

Example 1: if issubclass(int, object):
Int is a Subclass of Object

Example 2: if issubclass(list, object):
List is a Subclass of Object

Import and Module Management Examples

Problem: How to import a module dynamically?

Solution: import():
Description: "Imports a module dynamically."

module = __import__('module_name')

Example 1: module = __import__('math')
Math Module Imported

Example 2: module = __import__('random')
Random Module Imported

File and Directory Management Examples

Problem: How to open a file?

Solution: open():
Description: "Opens a file."

file = open('file.txt', 'r')

Example 1: file = open('example.txt', 'w')
File Opened for Writing

Example 2: file = open('data.csv', 'a')
File Opened for Appending

Problem: How to check if a path exists?

Solution: os.path.exists():
Description: "Checks if a path exists."

import os; exists = os.path.exists('file.txt')

Example 1: exists = os.path.exists('example.txt')
Path Exists: True

Example 2: exists = os.path.exists('missing.txt')
Path Exists: False

Exception Handling and Debugging Examples

Problem: How to manage exceptions?

Solution: try/except/finally:
Description: "Manages exceptions."

try: risky_operation() except Exception: handle_exception() finally: cleanup()

Example 1: try: divide(5, 0) except ZeroDivisionError: handle_error() finally: cleanup()
Exception Handled

Example 2: try: read_file('nonexistent.txt') except FileNotFoundError: handle_missing_file() finally: cleanup()
Exception Handled

Iterators and Generators Examples

Problem: How to get an iterator from a collection?

Solution: iter():
Description: "Returns an iterator."

it = iter(collection)

Example 1: it = iter([1, 2, 3])
Iterator Created

Example 2: it = iter(('a', 'b', 'c'))
Iterator Created

Problem: How to retrieve the next item from an iterator?

Solution: next():
Description: "Retrieves the next item from an iterator."

item = next(it)

Example 1: item = next(it)
Next Item: 1

Example 2: item = next(it)
Next Item: 'a'

Built-in Constants Examples

Problem: How to use Boolean constants?

Solution: True/False:
Description: "Boolean constants."

a = True; b = False

Example 1: a = True
Boolean Value: True

Example 2: b = False
Boolean Value: False

Problem: How to represent the absence of a value?

Solution: None:
Description: "Represents the absence of a value."

value = None

Example 1: result = None
No Assigned Value

Example 2: output = None
No Assigned Value

Command Line Arguments Examples

Problem: How to retrieve command-line arguments?

Solution: sys.argv:
Description: "Retrieves command-line arguments."

import sys; args = sys.argv

Example 1: import sys; args = sys.argv
Command-Line Arguments

Example 2: import sys; args = sys.argv[1:]
Command-Line Arguments (excluding script name)

Memory Management and Optimization Examples

Problem: How to trigger garbage collection?

Solution: gc.collect():
Description: "Triggers garbage collection."

import gc; gc.collect()

Example 1: import gc; gc.collect()
Garbage Collection Triggered

Example 2: import gc; gc.collect()
Garbage Collection Triggered

Problem: How to get the reference count of an object?

Solution: sys.getrefcount():
Description: "Gets the reference count of an object."

import sys; ref_count = sys.getrefcount(obj)

Example 1: import sys; ref_count = sys.getrefcount(some_object)
Reference Count: 5

Example 2: import sys; ref_count = sys.getrefcount(another_object)
Reference Count: 3

Comments

Popular posts from this blog

Feature Extraction From Audio| Audio feature extraction,| Feature matching,| speech recognition

Deploy django on ubuntu vps | Deploy python django on server | Make live your python app In ubuntu server | django on server

Dataiku Everyday AI | Introduction to Dataiku

Setup a Ubuntu VPS | Setup a Server | Make ready a server for python deployment | deploy python using apache and wsgi |

Python Framework

Edge Computing Vs Artificial Intelligence

Resume Parser Using Spacy

Speech Recognition | Natural Language Processing | NLP

What is server | Types of server | Servers