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

Python Functions

Uploaded by

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

Python Functions

Uploaded by

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

Strings

(immutable)
1. len() : returns length of a string, tells us the count of characters.
2. .upper(): converts the whole string into uppercase and returns a new string
3. .lower(): converts whole string into lowercase and returns a new string
4. .capitalize(): converts first letter of every word of the string to uppercase and rest remain in
lowercase
5. .title(): converts first letter of entire string to uppercase and rest remain in lowercase
6. .count(): counts the total number of occurrences of a substring in a string. Returns integer
value depending on number of occurrences. Returns 0 if substring is not found
​ count(substring,start,end+1) (default is checked for whole string)
7. .find(): finds and returns index number of a given substring in the entire string, it is in
accordance to the first occurrence of the substring. Returns -1 if substring is not found
​ find(substring,start,end+1)
8. .index(): returns smallest beginning index of a substring if it is found in the string. Raises
ValueError if not found.
​ index(substring,start,end+1)
9. .startswith(): returns True if a given string starts with the provided substring else returns
False.
​ startswith(substring,start,end+1)
10. .endswith(): returns True if a given string ends with the provided substring, else returns
False.
​ endswith(substring,start,end+1)
11. .isalnum(): returns True if all the characters in a string are alphanumeric - composed of
alphabets and numbers together, else returns False.
12. .isalpha(): returns True if the string contains only alphabets, else returns False.
13. .isdigit(): returns True if the string contains only digits(0-9), else returns False.
14. .isupper(): returns True if all the alphabets in the string are uppercase, else returns False.
15. .islower(): returns True if all the alphabets in the string are lowercase, else returns False.
16. .ispace(): returns True if all the characters are space, else returns False.
17. .lstrip(): used to remove specific characters from the left side of the string
18. .rstrip(): used to remove specific characters from the right side of the string
19. .strip(): used to remove characters from both sides of the string
20. .replace(): used to replace a given old string with a new string and returns a modified string.
​ [Link](oldstr,newstr,number of replacements)
21. .join(): joins the given string with each element of the iterable
22 .partition(): returns a tuple with exactly 3 elements. The middle element is the substring to
be searched and the partitioned with, if found. If not found, a black string appears. Parted based
on first occurrence only.
​ <str>.partition(<partition string>)
23. .split(): returns a list and splits the elements on the basis of the substring passed as a
parameter to the split function. If no parameter passed, split is done on the basis of space.
​ [Link](substr,no of splits)

Lists
(mutable)
1. Common functions-:
a.​ len(): returns length of the list
b.​ .count(): return count of a particular element passed as a parameter to the function. If
not found, returns 0. Doesn’t change the list.
c.​ .index(): returns the index of the first occurrence of the element passed as a parameter
to the function. If not found, generates ValueError.
2. .append(): inserts an element in the list at the end. Has only 1 parameter. Length of list
increases by one only.
.extend(): iterates over its parameter by adding each element of the list, extending it further by
as many elements as there were in the parameter.
3. list(): converts an iterable(tuple,string etc) into a list
4. .insert(): used to insert a value at a given index number. Has 2 parameters. Makes changes
in the list.
​ .insert(index,value)
5. .remove(): removes the given element from the list, in accordance with its first occurrence.
Takes the element to be removed as a parameter and the modifies the original list. If parameter
not found, generates ValueError. It is a value parameter. Doesn’t return any value at a given
index.
6. .pop(): returns value to be removed at a given index number passed as a parameter. If no
index provided, removes value at the last index of the list. If index passed doesn’t exist, raises
IndexError exceptions. Changes are made in the list. It is an index parameter. Returns value at
given index.
7. .reverse(): reverses the contents of a list and modifies the original list.
8. .sort(): modifies the contents of the list in ascending(default) or descending order. Changes
the list. Only works with lists. Doesn’t return any value.
​ <list>.sort(reverse=”True/False”)
9. .sorted(): generates new sorted list in ascending or descending order. Works with any
iterable. Returns new sorted list.
​ sorted(<list>)
10. max(), min(): returns maximum and minimum value from a given iterable. Values must be
homogenous.
11. sum(): sum of elements in the list, only works with numeric data.

In nested list, changes will only be reflected in the main list if we access exact locations of the
lists using range function.
Tuples
(immutable)
Common functions:
1.​ len(), count(), index(),minx(),max(),sum(),sorted()
tuple(): converts the iterable into a tuple

Dictionaries
(mutable)
1. Common functions:
a.​ .pop(<key>): deletes and returns the corresponding deleted value. Returns key error if
key passed doesn’t exist.
M = [Link]()
print(M) —> returns deleted value
b.​ max(),min()
i.​ max/min([Link]()): returns highest or lowest key with its value
ii.​ max/min(d) or max/min([Link]()): returns highest and lowest value among all
the values in the dictionary
iii.​ max/min([Link]()): returns highest and lowers key among all the keys in the
dictionary
c.​ .sorted()
i.​ L = sorted(D): returns a list of keys arranged in ascending or descending order
ii.​ L = sorted([Link]()): returns a list with tuple pairs of key and value arranged in
ascending order in accordance with the kys
iii.​ L = dict(sorted([Link]())): returns a dictionary with key and value pairs
arranged
iv.​ L = sorted([Link]()): returns a list of values of dictionary arranged in
ascending or descending order
2. dict(): converts the iterable(nested tuple of list) into a dictionary
​ <list>/<tuple> = dict(<list>/<tuple>)
3. .keys(): returns a tuple in which a list of keys of the dictionary is enclosed.
​ dict_keys([<keys>])
4. .values(): returns a tuple in which a list of values of the dictionary is enclosed.
​ dict_values([<values>])
5. .items(): returns list of (key,value) pairs of the dictionary, enclosed in a tuple
​ <dictionary>.items()
​ ([(k1,v1),(k2,v2)....])
6. .get(): returns value associated with key. Returns none or default value if the key is not found.
7. .update(): updates the value of the key if it exists. Adds it as a new item in the dictionary if it
doesn’t exist.
8. del: deletes an item of dictionary or the complete dictionary
​ del <dictionary>(<key>) - if no key provided, dictionary is deleted(NameError generated)
9. clear(): deletes the contents of the dictionary, not the dictionary itself.
10. .fromkeys(): creates a dictionary from a collection of keys(tuple or list) with a default value
for all if assigned, else None is assigned.
11. copy(): creates a copy of the dictionary.
​ D2 = [Link]() —> shallow copy
​ D2 = {}
​ for k,v in [Link]():
​ ​ D2[k] = v —--> shallow copy(changes reflected only in the copied one)
​ D2 = D1 —-> alias copy(changes reflected in both)
12. .popitem(): deletes the last item from the dictionary and returns the deleted item
13. setdefault():
​ i . returns value of key if it is in the dictionary
​ ii. Returns None if key is not in the dictionary and default value is not specified
​ iii. Returns default value if key is not present and default value is specified
​ <value> = <dict>.setdefault(<key>,<default value>)

Modules

[Link] module:
​ pi - value of pi
​ sqrt-square root
​ ceil - returns lower integer
​ floor - returns higher integer
​ pow-raised to the power
​ fabs-absolute value
​ sin,cos,tan-general
import math​ ​ ​ ​ ​ ​ ​ sine graph-: ​ ​
import math as <>
from math import <>​ ​ ​ ​ ​ ​
from math import *

sine graph-: same for cos and tan


from math import *
For D in range(0,361,20):
r=D*pi/180
s=int(10*sin(r))
print(D,”|”,(10+s)*” space”, “*”)

** pow() [Link]()
operator Built in function Belongs to math module

Gives integer result if both Gives integer result if both Always gives float result
operands are integers operands are integers

fastest - slowest

2. random() module
random(): - returns any random float value between 0.0 and 1.0
[Link](start,end): - returns any random integer value between start and end value,
both of them included
random,randrage(start,end+1,step): returns any random value between start and less than
end. Step is 1 by default

3. statistics() module
mean(<iterable>): returns mean of the data
Without module-:
L = [<data>]
print(sum(L)/len(L))

median(<iterable>): returns median of the data


Without module-:
L = [<data>]
[Link]()
n=len(L)
If n%2 == 0:
​ median = (L[n//2-1] + L[n//2])/2
else:
​ Median = (L[(n+1)//2])

mode: returns mode of the given data


Without module-:
L = [<data>]
d={}
for i in L:
​ If i in d:
​ ​ d[i]+=1
​ else:
​ ​ d[i]=1
If len([Link]()) == len(L):
​ print(“no mode possible”)
else:
​ max =0
​ for k,v in [Link]():
​ ​ If max<v:
​ ​ ​ max =v
​ ​ ​ mode =k
​ print(mode)

You might also like