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

Python DSA

A function is a reusable block of code that performs a specific task, promoting modularity and code reuse. It can accept default arguments, positional arguments (*args), and keyword arguments (**kwargs). The document also covers string manipulation, list operations, and dictionary features in Python, including methods for adding, removing, and searching elements.

Uploaded by

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

Python DSA

A function is a reusable block of code that performs a specific task, promoting modularity and code reuse. It can accept default arguments, positional arguments (*args), and keyword arguments (**kwargs). The document also covers string manipulation, list operations, and dictionary features in Python, including methods for adding, removing, and searching elements.

Uploaded by

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

What is a Function? s.

split(',') # ['Python', 'is', 'an', 'interpreted', 'language']


A function is a reusable block of code that performs a specific 🧵 join()
task. It helps in modularity and code reuse. ' '.join(["Python is", "awesome"]) # 'Python is awesome'
Default arguments allow you to define default values for 🔍 find() & rfind()
parameters in a function. When a value is not provided by the s = "Python is a programming language"
caller, the default value is used. [Link]('i') # 7
What is *args? [Link]('i') # 20
Use *args when you don’t know how many values (numbers, [Link]('z') # -1 (not found)
names, etc.) will be passed to a function. 🔍 index() & rindex()
It collects positional arguments (those without a name) into a [Link]('p') #0
tuple. [Link]('p',10,20) # 12
What is **kwargs? [Link]('z') # ValueError
Use **kwargs when you don’t know how many named values 🔤 ord() & chr()
(like name="John", age=25) will be passed. ord('a') # 97
It collects keyword arguments into a dictionary. chr(65) # 'A'
A string is a datatype that is used to store text. It is made up function to slice first 2 & last 2 chars from a given a string
of letters, numbers, spaces,/symbols,written between quotes def string_both_ends(str):
🔹 1. Cannot Add Elements to Strings return str[:2] + str[-2:]
Strings are immutable, so you cannot use methods like print(string_both_ends('python programming'))
append(), extend(), or insert(). Expression Result
However, you can create new strings by concatenation: s 'python'
Operation Example Result s[-1] 'n'
Concatenation 'a' + 'b' 'ab' s[-2] 'o'
Repetition 'ab' * 3 'ababab' s[-6] 'p'
Join elements ' '.join(['a','b']) 'a b' s[-4:-1] 'tho'
s[-4:] 'thon'
🔹 2. Remove/Replace Elements
s[:-2] 'pyth'
Example Result
s[::-1] 'nohtyp'
'apple'.replace('p','') 'ale'
s[-1:-4:-1] 'noh'
' hi '.strip() 'hi'
s[-2:-5:-1] 'oht'
Note:You can't remove characters using pop()/del like in
lists. You must create a new string. s[-3:-6:-1] 'hyt'
s[-5:-2] 'yth'
🔹 3. Search / Count s[-2:-6:-2] 'ot'
Method Example Result s[-3::-1] 'htyp'
index() & rindex (value 1 (first s[-1:-6:-1] 'nohty'
'apple'.index('p')
error) occurrence) String traversal using while loop
find() & rfind() (-1) 'apple'.find('z') -1 (if not found) s="Python"
count() 'apple'.count('p') 2 i=0
while (i < len(s)):
in 'p' in 'apple' True
print(s[i], end= '')
startswith() 'apple'.startswith('a') True i=i+1
endswith() 'apple'.endswith('e') True Printing locations of a substring with index location
s="a is a then what is a"
🔹 4. Sort & Reverse (Indirect) pos=-1
Strings don’t have .sort() or .reverse() methods, but you can while True:
use these alternatives: pos=[Link]("a",pos+1)
Operation Example Result if pos==-1:
Sorted sorted('cba') ['a', 'b', 'c'] break
Reverse iterator ''.join(reversed('abc')) 'cba' print(pos)
Manual reverse 'hello'[::-1] 'olleh' Deposit & withdraw:
def func(l):
🔹 5. Copying Strings d,w=0,0
Since strings are immutable, copies are easy: for i in l:
Method Syntax Example Result l_new=[Link](":")
Slice copy s[:] 'hello'[:] 'hello' print(l_new)
if l_new[0]=="D":
Constructor str(s) str('hello') 'hello'
d=d+int(l_new[1])
Assign s2 = s1 b = a Points to same value elif l_new[0]=="W":
🔍 Membership Operators w=w+int(l_new[1])
"Program" in "Python Programming" # True (case-sensitive) return (d-w)
"Program" not in "Python Programming" # False print(func(["D:300","D:300","W:200","D:100"]))
🪓 split() Counting no of occurances of a substring
s = "Python,is,an,interpreted,language" s = "abcabcabc"
sub = 'abc' print(s)
count = 0
for i in s:
for i in range(len(s) - len(sub) + 1): if len(i)%2==0:
if s[i:i+len(sub)] == sub: print(i)
count = count + 1 str = "ab abc abcd a"
print(f"'{sub}' appears {count} times") even_words(str)
def func(a): def func(str1, str2):
i=0 for i in str1:
a_new="" if i in str2:
while len(a)>i: print(i, end="")
a_new=a[i]+a_new
i=i+1 func('rose', 'gooise')
return a_new Lists:
print(func("omlal")) 🔹 Python List – Key Features (Short)
def func(s): 1. Data Structure – Holds any data type (int, float, str,
if len(s)<=2: bool, etc.).
return s 2. Mutable – Can be changed (add, update, delete
elif s[-3:]=="ing": items).
return s+"ly" 3. Ordered – Maintains insertion order; supports
else: indexing & slicing.
return s+"ing" 4. Supports Operations – Insert, update, delete,
print(func("omlally")) search, sort, etc.
finds the number of letters and digits in the sentence. 5. Syntax – Defined using square brackets [ ].
s = 'year 2025' 🔹 1. Add Elements
d=l=0 Method Syntax Example Result
Adds 10 to end of
for i in s: append() [Link](value) [Link](10)
list
if [Link]():
d=d+1 [Link]([4, Adds all values
extend() [Link](iterable)
elif [Link](): 5]) from [4, 5]
l=l+1 Inserts 99 at
insert() [Link](index, value) [Link](1, 99)
else: position 1
pass
🔹 2. Remove Elements
print("Letters", l) Method Syntax Example Result
print("Digits", d) Removes first
remove() [Link](value) [Link](5)
def reverse_str(s): occurrence of 5
s_new = '' Removes value at
for i in s: pop() [Link](index) [Link](2) index 2 (default is
s_new = i + s_new last)
return s_new clear() [Link]() [Link]() Removes all value

print(reverse_str("Welcome")) del
del l[1]
files = ["[Link]", "[Link]", "[Link]"] (statement) del list[index] del (statement)
for i in files: del list[start:end]
if [Link](("doc", "data")):
print(f"{i} is a text file")
else: 🔹 3. Search / Count
print(f"{i} is not a text file") Method Syntax Example Result
s = "[Link]" index() [Link](value) [Link](7) Returns index of 7
print([Link](".pdf")) Returns how many times
count() [Link](value) [Link](2)
print([Link](".docx")) 2 appears
Removing specified character in a given srting
def remove(s, i): 🔹 4. Sort & Reverse
a = s[:i] Method Syntax Example Result
b = s[i+1:] Sorts list
return a+ b in
sort() [Link]() [Link]()
ascendin
s = "Python" g order
i=2
Sorts
print(remove(str, i)) sort(reverse=Tr [Link](reverse=T [Link](reverse=Tr
descendi
program to print even length words in a string ue) rue) ue)
ng
def even_words(s):
Reverses
s = [Link](' ') reverse() [Link]() [Link]()
the list
Method Syntax Example Result program which returns true if one of the first 4 elements
Returns in list is 9.
sorted def func(l,n):
sorted() sorted(list) sorted(a) if n in l[:4]:
copy of
list return True
return False
🔹 5. Copying Lists print(func([9,9,2,3,9],1))
Method Syntax Example Result Removing Duplicates
[Link]() def func(l):
copy() or l2 = b = [Link]() Makes a copy of the list l_new=[]
l1[:] for i in l:
if i not in l_new:
l_new.append(i)
a = ['a', 'b']
return l_new
c="string"
print(func([1,-1,9,9,1,1,1]))
[Link](c)
print(a) Function to check a list is empty or not
['a', 'b', 's', 't', 'r', 'i', 'n', 'g'] list1=[]
if not list1:
print("nothig")
l = ['aaaaaa22222', 'baaaaa']
[Link](key=len) In two lists if they have at least one common returns True
print(l) def func(l1,l2):
for i in l1:
if i in l2:
l=[100,'python',50.8,'a',200,300]
return True
i=0
return False
print(func([-1,9,9],[-1,11,-1]))
while i < len(l):
print(l[i])
find common elements
i=i+1
def func(l1, l2):
[Link](20,'True') c = []
print (l) #[100, 'python', 50.8, 'a', 200, 300, 'True'] for i in l1:
l=[100,'python',50.8] if i in l2 and i not in c:
[Link]("string") [Link](i)
print (l) #[100, 'python', 50.8, 's', 't', 'r', 'i', 'n', return c
'g'] List Comprehension:
l = ['banana', 'pie', 'Washington', 'book'] Syntax:[expression for item in iterable if condition]
[Link](key=len, reverse=True) # In-place Nested Loops:[expression for item1 in iterable1 for item2 in
print(l) #['Washington', 'banana', 'book', 'pie'] iterable2]
Multiplies all the items in a list l=[i for i in "computer"]
def multiply_list(l): print(l)
tot = 1 l=["allow","sequences","to","be","built","from","other","sequ
for i in l: ences"]
tot = tot * i l=[[Link]() for i in l]
return tot print(l)
# Convert height to feet 1 cm = 0.0328 feet
print(multiply_list([1,2,5,9,10]))
h_cms = [('akshay',183),('rahul',171),('sourav',179),
Get the largest number from a list ('virat',190),('rohit',165)]
def func(l): h_fts=[(i[0],round(i[1]*0.0328),2) for i in h_cms]
max=l[0] print(h_fts)
for i in range(len(l)):
Finding common elements in list
if l[i]>max:
a = [1, 2, 3, 4, 6]
max=l[i]
b = [2, 3, 4, 5, 7, 2]
return max0
l=[i for i in a for j in b if i==j]
print(l)
print(func([-1,-6,-9,-11,2]))
✅ 8. Nested Loops (Multiplication Table)
list of words that are longer than n from a list of words.
l1 = [20,40,60]
def func(l,n):
l2 = [2,4,6]
l_new=[Link](" ")
l1 = [x * y for x in l1 for y in l2]
result=[]
print(l1)
for i in range(len(l_new)):
if len(l_new[i])>=n: Dictionary:
[Link](l_new[i]) Features:
return result 1. Unordered → No fixed order (in concept).
print(func("The quick brown fox jumps over the lazy dog",5)) 2. Mutable → Values can be changed.
3. Keys must be unique & immutable → e.g., string,
number, tuple.
4. Values can be of any data type → int, list, dict, etc. freq[num] = 1
5. Each key-value pair is called an item.
6. Defined using curly braces {}. print(freq) # {1: 2, 2: 2, 3: 1, 4: 1}
🔹 1. Accessing & Retrieving def func(s):
Method / freq={}
Syntax Example Result s=[Link]()
Statement
student = {'name': print(s)
Access for i in s:
dict[key] 'Alice'}; 'Alice'
value if i in freq:
print(student['name'])
student = {'age': 21}; freq[i]=freq[i]+1
get() [Link](key) 21 else:
print([Link]('age'))
freq[i]=1
student = {'name':
dict_keys(['name', return freq
keys() [Link]() 'Alice', 'age': 21};
'age']) print(func("omlal sai kantekar sai ram ramu"))
print([Link]())
student = {'name': swap keys & values
dict_values(['Alice',d={1:2,2:3,10:11}
values() [Link]() 'Alice', 'age': 21};
21]) d1={v:k for k,v in [Link]()}
print([Link]())
print(d1)
student = {'name':
dict_items([('name',keys & even or odd
items() [Link]() 'Alice', 'age': 21};
'Alice'), ('age', 21)])nums = [1, 2, 3, 4]
print([Link]())
2. Adding & Updating result = {x: ('even' if x%2==0 else 'odd') for x in nums}
Method Syntax Example Result # Output: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even'}
Add / Adds letters = ['a', 'b']
dict[key] = value student['grade'] = 'A'
Update 'grade': 'A' numbers = [1, 2]
d1={(l,n):l+str(n) for l in letters for n in numbers}
[Link]({'age': Updates
update() [Link](other_dict) print(d1)
22}) 'age' to 22
🔹 3. Removing Elements Dict= {'eooooa': 1, 'aas': 2, 'udd': 3, 'sseo': 4, 'werwi': 5}
Method Syntax Example Result sorted_dict = {i: Dict[i] for i in sorted(Dict)}
print(sorted_dict)
student = {'name':
'Alice'}; a={i: chr(97+i) for i in range(26)}
pop() [Link](key) {} print(a, end="")
[Link]('name');
print(student) d=
student = {'name': ["allow","sequences","to","be","built","from","other","sequen
'Alice', 'age': 21}; Removes last ces"]
popitem() [Link]()
[Link](); inserted item
print(student) {i:len(i) for i in d}
student = {'age': 21}; del scores = {'maths': 55, 'physics': 65, 'chemistry': 75}
del keyword del dict[key] student['age']; {} new_marks = {sub: marks + 5 for (sub, marks) in
print(student) [Link]()}
print(new_marks)
student = {'name':
clear() [Link]() 'Alice'}; [Link](); {} scores = {'maths': 50, 'physics': 60, 'chemistry': 75}
print(student) new={k:v for (k,v) in [Link]() if v%2==0 if v>50}
print(new)
🔹 4. Copying & Creating def traverse(scores,value):
Method Syntax Example Result for k,v in [Link]():
if v==value:
student = {'age': 21};
return k,v
new_student =
copy() [Link]() {'age': 21} print(traverse({'maths': 50, 'physics': 60, 'chemistry': 75},50))
[Link]();
print(new_student) d = {'eooooa': 1, 'aas': 2, 'udd': 3, 'sseo': 4, 'werwi': 5}
keys = ['a', 'b'];
print(sorted(d, key=len))
[Link](keys, new_dict = {'a': 0, 'b':
fromkeys() Case_study:Super Market
value) [Link](keys, 0}
0); print(new_dict)
 all(dict) → checks if all keys are truthy.
 all([Link]()) → checks if all values are truthy.
 any([Link]()) → checks if any value is truthy.
arr = [1, 2, 2, 3, 1, 4]
freq = {}

for num in arr:


if num in freq:
freq[num] += 1
else:
Method Syntax Example Result
Returns reversed
reversed() tuple(reversed(t)) tuple(reversed(a))
tuple

🔹 5. Copying Tuples
Method Syntax Example Result
Copy t2 = t1 b = a Both refer to same tuple
Slice Copy t2 = t1[:] b = a[:] Creates a copy of the tuple

data5=(1,2,3,4)
data6=(1) #error
data7 = data5 + data6

print (data7)
sum and product of all elements in a tuple of numbers.
def func(a):
s=0
p=1
for i in a:
s=s+i
p=p*i
return (s,p)
print(func((11,4)))
function that takes two tuples and returns a tuple
containing the element-wise sum of the input tuples
def func(a,b):
if len(a)!=len(b):
raise ValueError("not match")
l=tuple(i+j for i,j in zip(a,b))
return l
print(func((1,2,3),(3,2,10,9)))
Tuple: function that takes a tuple & a value, & returns a new
✅ Common Methods in Both str and list tuple with value inserted at beginning of original tuple
Method Description Notes def func(t,v):
return ((v,)+t)
Returns (index, Useful in loops over both
enumerate(obj) print(func((1,2,3),9))
value) pairs strings and lists
function that takes a tuple of tuples and returns a tuple
🔹 1. Creating / Adding Elements (Workarounds) containing the diagonal elements of the input.
def func(t):
Method Syntax Example Result
return tuple(t[i][i] for i in range(len(t)))
tuple1 + Returns new tuple print(func(((1, 2, 3),(4, 0, 6),(7, 8, 1))))
Concatenation a + (10,)
tuple2 with 10 added
a, b = (10, 20, 30)
Repeats the tuple
Repetition tuple * n a*3
3 times print(a)
list(t) → print(b)
tuple(list(a) + Add element by
Conversion modify → print(c) #ValueError: too many values to unpack(expected
[10]) converting to list
tuple(l) 2)
function that takes a tuple of strings and concatenates
🔹 2. Remove Elements (Workarounds) them, separating each string with a space.
Method Syntax Example Result def func(t):
list(t) → Remove by return " ".join(t)
Conversion modify → tuple(list(a).remove(5)) converting to print(func(('Hello', 'World', 'from', 'Python')))
tuple(l) list function that takes two tuples and returns a tuple
containing the common elements of the input tuples.
🔹 3. Search / Count def func(t1, t2):
Method Syntax Example Result return tuple(set(t1) & set(t2))
Returns index of first func((1, 2, 3, 4, 5),(4, 5, 6, 7, 8))
index() [Link](value) [Link](7)
occurrence of 7 Unpack a tuple in several variables
Returns number of t = 1,2,3
count() [Link](value) [Link](2)
times 2 appears
n1, n2, n3 = t
🔹 4. Sort & Reverse (Workarounds) print(n1 + n2 + n3)
Method Syntax Example Result Remove an item from a tuple
sorted() sorted(tuple) sorted(a) Returns sorted list t = ("p", "y", "t", "h", "o", "n")
l = list(t) Operation Syntax/Example Result
[Link]("h") Difference a - b, [Link](b) {1, 2}
t = tuple(l) Symmetric a ^ b,
print(t) {1, 2, 4, 5}
Difference a.symmetric_difference(b)
Reverse a tuple Subset a <= b, [Link](b) False
x = ("tuple")
Superset a >= b, [Link](b) False
y = reversed(x)
print(type(y)) Disjoint [Link](b) False
print(tuple(y))
Output:<class 'reversed'> ('e', 'l', 'p', 'u', 't') 🔹 3. Frozenset (Immutable Set)
Remove an empty tuple(s) from a list of tuples Concept Example Result
l = [(), (),('a', 'b'), ('a', 'b', 'c'), ('d')] fSet = frozenset({'a', 'e', 'i',
Create
l = [i for i in l if i] frozenset(['a','e','i','o','u']) 'o', 'u'})
print(l) Empty
frozenset() frozenset()
Check whether an element exists within a tuple frozen
addCodeaddText Dictionary frozenset({'name': 'John'})
frozenset({'name'})
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 key → keys only
Immutable fSet[0] = 'z' TypeError
print(4 in tuplex)
print(51 in tuplex) [Link]([7,8],{1,2,9})
Sets: numbers
1. Using Curly Braces {} o/p: {1, 2, 3.5, 7, 8, 9, 10, 11}
s = {1, 2, 3}
2. Using set() Constructor days={'Monday','Tuesday','Wednesday','Thursday','Friday','Sa
s = set() # Empty set (⚠️`{}` creates a dictionary) turday','Sunday'}
# A set is mutable, but may not contain mutable items like a max(days) # Wednesday
list, set, or even a dictionary.
✅ Python Built-in Functions (With Examples)
Properties of Sets
 Unordered: No indexing or slicing.
🔹 1. zip():Combines multiple iterables (lists, tuples, etc.)
 Mutable: You can add or remove elements.
element-wise into tuples.
 Unique Elements: No duplicates allowed.
 Heterogeneous: Can contain mixed data types (but Syntax zip(iter1, iter2, ...)
only hashable types). ✅ Examples:name = ["Akshay", "Dravid", "Sachin"]
 # since sets do not support indexing, they cannot be roll_no = [10, 20, 30]
sliced. marks = [90, 88, 75]
 a={1,2,3}
 a[0:2] mapped = zip(name, roll_no, marks)
print(list(mapped))
🔹 1. Creating / Adding Elements
Output:
Result (Set after [('Akshay', 10, 90), ('Dravid', 20, 88), ('Sachin', 30, 75)]
Method Syntax Example
execution) # Uneven length
Literal {...} a = {1, 2, 3} a = {1, 2, 3} marks = [90]
Empty print(list(zip(name, roll_no, marks)))
set() a = set() a = set()
Set Output:[('Akshay', 10, 90)]
add() [Link](x) [Link](4) a = {1, 2, 3, 4}
[Link]([5, 6], a = {1, 2, 3, 4, 5, 6, 🔹 2. map()Applies a function to each element of an iterable.
update() [Link](iter)
{7}) 7} Syntax map(function, iterable)
✅ Examples:
🔹 2. Remove Elements def sq(n): return n * n
Method Syntax Example Result nums = [1, 2, 3, 4, 5]
Removes 2, error if not print(list(map(sq, nums)))
remove() [Link](x) [Link](2) Output:[1, 4, 9, 16, 25]
found
Silently does nothing if # Using tuple as output
discard() [Link](x) [Link](10) def square(x): return x * 2
absent
lst = [1, 2, 3, 4, 5]
Removes and returns
pop() [Link]() [Link]() print(tuple(map(square, lst)))
any item
Output:(2, 4, 6, 8, 10)
clear() [Link]() [Link]() Empties the set
🔹 [Link]():Filters elements where the function returns True.
Syntax filter(function, iterable)
🔹 4. Set Operations ✅ Examples:alphabets = ['a', 'b', 'd', 'a', 'e', 'i', 'j', 'o']
Let a = {1, 2, 3}, b = {3, 4, 5} def filterVowels(char):
Operation Syntax/Example Result return char in ['a', 'e', 'i', 'o', 'u']
b,
Union `a
[Link](b)` filtered = list(set(filter(filterVowels, alphabets)))
Intersection a & b, [Link](b) {3} print(filtered
Output:['o', 'e', 'i', 'a']
lst = [10, 14, 18, 19, 22, 24] 🔹 2. Find All Matches
def checkAge(age): return age > 18 Purpose
print(list(filter(checkAge, lst))) Output/
Method (Definition Example (Code)
Output:[19, 22, 24] Result
)
Returns all
🔹 4. enumerate():Adds a counter to iterable, returns as matching [Link](r"\d+", "There
(index, item) pairs. findall() ['3', '12']
substrings are 3 cats and 12 dogs.")
Syntax enumerate(iterable, start=0) in a list
✅ Examples: Returns [[Link]() for m in
programming = ["Python", "Programming", "Is", "Fun"] iterator of [Link](r"\\b\\w{4}\\
print(list(enumerate(programming))) finditer() ['This', 'test']
match b", "This test has four
Output: objects words.")]
[(0, 'Python'), (1, 'Programming'), (2, 'Is'), (3, 'Fun')]
# Starting index from 100 🔹 3. Replace and Substitute
print(list(enumerate(programming, 100))) Purpose
Output:[(100, 'Python'), (101, 'Programming'), (102, 'Is'), Method Example (Code) Output/Result
(Definition)
(103, 'Fun')]
Replaces all [Link](r"\d+", "#",
sub() matches with "User123 and 'User# and ID#'
🔹 5. sorted():Returns a sorted list from the given iterable.
something else ID456")
Syntax sorted(iterable, key=None, reverse=False)
Same as sub but
✅ Examples: a = [1, 4, 3, 2, 8] [Link](r"\d+",
also returns ('One# Two#
print(sorted(a)) subn() "#", "One1 Two2
replacement Three#', 3)
print(sorted(a, reverse=True)) Three3")789+
count
Output:[1, 2, 3, 4, 8]
[8, 4, 3, 2, 1]
🔹 4. Split by Pattern
names = ['Guido van Rossum', 'Bjarne Stroustrup', 'James
Gosling'] Purpose
Method Example (Code) Output/Result
print(sorted(names, key=lambda name: [Link]()[-1])) (Definition)
O/p:['James Gosling','Guido van Rossum','Bjarne Stroustrup'] Splits string [Link](r",\\s*",
['apple', 'banana',
split() where the "apple, banana,
'cherry']
🔹 6. max()&min():Returns largest/small item from iterable. pattern matches cherry")
Syntax max(iterable, key=func) / min(iterable, key=func)
✅ Example: 🔹 5. Compile Regex (for Reuse)
studmarks = [('ABC', 35), ('CDE', 25), ('XYZ', 30),('PQR', Purpose
Method Example (Code) Output/Result
20)] (Definition)
print(max(studmarks, key=lambda student: student[1])) Pre-compile pattern =
print(min(studmarks, key=lambda student: student[1])) a pattern to [Link](r"[a-z]+");
compile() ['abc']
Output:('ABC', 35) use multiple [Link]("ABC
('PQR', 20) times abc")

🔹 7. reduce() (from functools):Applies a rolling function to 🔹 6. Match Object Methods


pairs of values cumulatively. text = "Phone: 408-555-1234"
Syntax reduce(function, iterable) m = [Link](r"(\\d{3})-(\\d{3})-(\\d{4})", text)
✅ Example:from functools import reduce Method Purpose (Definition) Example Output/Result
print(reduce(lambda x, y: x + y, [1, 2, 3, 4])) Returns matched
group() [Link]() '408-555-1234'
Output:10 string
Regular Expressions in Python : It is a special pattern used start() Returns start index [Link]() 7
to search, match, or extract text. It helps find specific parts end() Returns end index [Link]() 20
of a string, like phone numbers, capital letters, or words. Returns (start, end)
ex: Find all capital letters: [Link](r"[A-Z]", text) span() [Link]() (7, 20)
tuple
 Find phone no: [Link](r"\d{3}-\d{3}-\d{4}", text) Returns all grouped ('408', '555',
🔹 1. Match Patterns groups() [Link]()
matches '1234')
Purpose group(1) Returns specific group [Link](1) '408'
Method Example (Code) Output/Result
(Definition)
Matches a 🔹 7. Short Regex Patterns
pattern only [Link](r"\d+", Identifiers for Characters in Patterns
match() '123'
at the start "123abc").group() Output /
of the string Character Description Example Pattern Code
Match
Finds the [Link](r"file_\d\d",
[Link](r"[A-Z]", \d Digit (0–9) ['file_25']
first match "file_25")
search() "find A 'A'
anywhere in
letter").group() Alphanumeri [Link](r"\w-\w\w\w",
the string \w ['A-b_1']
c "A-b_1")
Matches the [Link](r"\w+",
fullmatch() 'hello123' \s Whitespace [Link](r"a\sb\sc", "a b ['a b c']
entire string "hello123").group()
Output /
Character Description Example Pattern Code
Match Pattern Description Example Code Output
c") Match all non-digit [Link](r"[^0-9]", ['a', 'b', 'c',
[Link](r"\D\D\D", [^0-9]
\D Non-digit ['ABC'] characters "a1b2c3!") '!']
"ABC123")
Non- [Link](r"\W\W\W\W\ # Inclusion
\W ['*-+=)']
alphanumeric W", "*-+=)") string='''123345678'''
Non- [Link](r"\S\S\S\S", print([Link](r"[123]",string))
\S ['Yoyo']
whitespace "Yoyo test") SQLite is a small database that stores data in a single
file and doesn't need a server.
📌 Quantifiers Database: it is a place where we store data in an organized
Example Pattern
Character Description Output / Match way so we can use it easily.
Code 🔹 1. Basic Setup
One or more [Link](r"\w-\w+", import sqlite3
+ ['A-b1_1']
times "A-b1_1") conn = [Link]("[Link]") #or ':memory:'for
Exactly 3 [Link](r"\D{3}", temporary
{3} ['abc']
times "abc123")
Between 2 [Link](r"\d{2,4}", 🔹 2. Create Table
{2,4} ['123'] [Link]('''
and 4 times "123")
3 or more [Link](r"\w{3,}", CREATE TABLE COMPANY (
{3,} ['anycharacters'] ID INT PRIMARY KEY NOT NULL,
times "anycharacters")
NAME TEXT NOT NULL,
Zero or [Link](r"A*B*C*",
* ['AAACC'] AGE INT NOT NULL,
more times "AAACC")
ADDRESS CHAR(50),
[Link](r "\ ['name', 'names'] SALARY REAL
Once or
? w+es?","name names" );''')
none
)
🔹 3. Insert Data
📌 Anchors – Start and End [Link]("INSERT INTO COMPANY (ID, NAME,
Pattern Meaning Example Code Output AGE, ADDRESS, SALARY) VALUES (1, 'Paul', 32,
^ Start of string [Link](r"^a", "abc") ['a'] 'California', 20000.0)")
$ End of string [Link](r"c$", "abc") ['c'] [Link]()

🔹 8. Sets, Ranges, and Groups 🔹 4. Select Data


Patter Meanin # All records
Example (Code) Output cursor = [Link]("SELECT * FROM COMPANY")
n g
Match for row in cursor: print(row)
any one [Link](r"[abc]",
[abc] ['b', 'a', 'c', 'a', 'b'] # Fetch all
of a, b, "bravo cab")
or c rows = [Link]()
Match
anything [Link](r"[^0- # Fetch one
[^0-9] ['a', 'b', 'c'] row = [Link]()
not a 9]", "a1b2c3")
digit
# Fetch many
Match either ab or
`(ab cd)` `[Link](r"(ab records = [Link](3)
cd
Match
🔹 5. Update Records
exact
[Link](r"\\ [Link]("UPDATE COMPANY SET SALARY = 25000
\bword\ word
bword\\b", "a word ['word'] WHERE ID = 1")
b using
in a sentence") [Link]()
boundari
es
🔹 6. Delete Records
[Link](r'cat(fish|nap| [Link]("DELETE FROM COMPANY WHERE ID =
`cat(fis
nap)` Match start & stop claw)',t) 2")
h
[Link]()
🔹 9. Useful Flags 🔹 7. Queries & Filters
Flag Purpose Example (Code) Output # WHERE with AND
[Link]("hello", SELECT * FROM COMPANY WHERE AGE >= 25 AND
re.I Case-insensitive 'HELLO'
"HELLO", re.I).group() SALARY >= 65000;
Multiline mode (^, [Link]("^a", "a\\nb\\na",
re.M ['a', 'a']
$ line-based) re.M) # WHERE with OR
Dot . matches [Link]("a.+b", "a\\n\\ SELECT * FROM COMPANY WHERE AGE >= 25 OR
re.S 'a\\n\\nb' SALARY >= 65000;
newline nb", re.S).group()
🔹 1. Joins
# LIKE import sqlite3
SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%'; db = "[Link]"
conn = [Link](db)
# IN / NOT IN [Link]("PRAGMA foreign_keys = ON;")
SELECT * FROM COMPANY WHERE AGE IN (25, 27);
SELECT * FROM COMPANY WHERE AGE NOT IN (25, 🔹 2. Create Tables
27); COMPANY Table
[Link]('''
# BETWEEN CREATE TABLE COMPANY (
SELECT * FROM COMPANY WHERE AGE BETWEEN ID INT PRIMARY KEY,
25 AND 27; NAME TEXT NOT NULL,
AGE INT NOT NULL,
🔹 8. Order & Grouping ADDRESS TEXT,
# ORDER BY SALARY REAL
SELECT * FROM COMPANY ORDER BY SALARY );''')
DESC; DEPARTMENT Table
SELECT * FROM COMPANY ORDER BY NAME; [Link]('''
CREATE TABLE DEPARTMENT (
# GROUP BY ID INT PRIMARY KEY,
SELECT NAME, SUM(SALARY) FROM COMPANY DEPT TEXT NOT NULL,
GROUP BY NAME; EMP_ID INT,
FOREIGN KEY (EMP_ID) REFERENCES
🔹 9. Schema Info COMPANY(ID)
[Link]("SELECT name FROM sqlite_schema WHERE );''')
type='table'")
🔹 5. JOINS
🔹 10. Parameterized Queries ✅ CROSS JOIN
[Link]('INSERT INTO languages (subject, marks) [Link]("SELECT EMP_ID, NAME, DEPT FROM
VALUES (?, ?)', ('Python', 300)) COMPANY CROSS JOIN DEPARTMENT;")
📌 All possible combinations (x * y rows)
🔹 11. In-Memory DB Example
con = [Link](":memory:") ✅ INNER JOIN
cur = [Link]() [Link]("SELECT EMP_ID, NAME, DEPT FROM
[Link](""" COMPANY INNER JOIN DEPARTMENT ON
CREATE TABLE samples(id,value); [Link] = DEPARTMENT.EMP_ID;")
INSERT INTO samples(id, value) VALUES 📌 Only matching rows from both tables.
('123','abcdef');
""") ✅ LEFT OUTER JOIN
[Link]("SELECT EMP_ID, NAME, DEPT FROM
🔹 12. Errors Explained COMPANY LEFT OUTER JOIN DEPARTMENT ON
 table already exists: When trying to create an existing [Link] = DEPARTMENT.EMP_ID;")
table again. 📌 All rows from COMPANY + matched DEPARTMENT
 UNIQUE constraint failed: Duplicate value for a rows (else NULL)
column with PRIMARY KEY or UNIQUE.
🔸 6. Indexing
Code:
[Link]("CREATE INDEX idx_salary ON
COMPANY(SALARY);")
Use:Speeds up queries using the SALARY column (like
WHERE, ORDER BY). Improves performance on large
datasets.

🔸 7. ALTER TABLE
Code:
[Link]("ALTER TABLE COMPANY ADD COLUMN
EMAIL TEXT;")
Use:Used to add new columns to an existing table without
dropping or recreating it.

🔸 9. Backup Database
import shutil
[Link]("[Link]", "emp1_backup.db")
Use:Creates a backup copy of your database file for safety or
versioning purposes.
🔷 JSON METHODS (with Examples + Outputs)
📘 What is JSON?
JSON (JavaScript Object Notation):lightweight format for
storing and exchanging data.
 It is easy for humans to read and write
 Easy for machines to parse and generate
 Mostly used in web APIs,config files&data
exchange

✅ JSON Example
{
"name": "VCube",
"technologies": ["C", "Java", "Python"],
"location": "Hyderabad",
"active": true
}
 A string ("name")
 A list ("technologies")
 A boolean (true)

🧠 JSON Rules
Rule Example
Data is in key-
"name": "VCube"
value pairs
Keys are strings "location"
Values can be: string, number, object, array, boolean, null
Arrays use
["C", "Java"]
square brackets
Objects use curly
{ "a": 1 }
brackets
Strings must use
"Hello"
double quotes
Method Description
[Link](json_str) JSON string → Python object/dict
[Link](python_obj) Python object/dict → JSON string
[Link](file) JSON file → Python object
[Link](obj, file) Python object → JSON file
[Link](..., indent) Pretty print JSON
country {'name': 'India'}

✅ [Link]('rank').text and .get('attribute')


for country in [Link]('country'):
rank = [Link]('rank').text
name = [Link]('name')
print(name, rank)
📤 Output:Singapore 1
India 4

✅ [Link]('attr', value) and [Link]('[Link]')


Purpose: Modify XML values and save the file
for rank in [Link]('rank'):
new_rank = int([Link]) + 1
[Link] = str(new_rank)
[Link]('updated', 'yes')

[Link]('[Link]')
📤 Output in [Link]:<rank updated="yes">2</rank>
🟪 What is XML?
XML (eXtensible Markup Language) is used to store and ✅ [Link](xml_string)
transport data. Purpose: Load XML data directly from a string
It is human-readable and machine-readable — similar to data = '''
HTML but made for data not webpages. <Company>
<name>VCube</name>
✅ XML Example <type>Online</type>
<student> <email id="support@[Link]" mobile="1234-
<name>Rohith</name> 567890"/>
<id>007</id> </Company>'''
<branch>CSE</branch>
</student> tree = [Link](data)
print([Link]('name').text)
print([Link]('email').get('id'))
✅ XML Structure & Rules
📤 Output:VCube
Element Description
support@[Link]
<tag>value</tag> XML uses tags like HTML
Must have 1 root tag All elements are inside a single main tag ✅ Student Example
Attributes Tags can have attributes like id="123" input = '''
Case-sensitive <Name> ≠ <name> <student>
Tags must be closed Every <tag> must have a closing </tag> <user x='1'>
📋 Summary: XML Methods <id>007</id>
Method Description <name>Virat</name>
[Link](file) Parse XML file </user>
<user x='2'>
getroot() Get root element
<id>010</id>
[Link], [Link] Get tag name or attributes <name>Rohith</name>
[Link]('tag').text Get value from sub-element </user>
[Link]('attribute') Get value of an attribute </student>'''
[Link](xml_string) Load XML from string
[Link](attr, val) Update/set an attribute student = [Link](input)
[Link]('[Link]') Save modified XML to file lst = [Link]('user')
[Link]('tag') Find all children with a tag
for user in lst:
[Link]('tag') Iterate through all matching tags
print("Name :", [Link]('name').text)
✅ [Link]('[Link]') + [Link]() print("ID :", [Link]('id').text)
Purpose: Load XML from a file and get root tag print("x :", [Link]('x'))
import [Link] as ET print()
tree = [Link]('country_data.xml') 📤 Output:Name : Virat
root = [Link]() ID : 007
print([Link]) x :1
📤 Output:data
Name : Rohith
✅ [Link], [Link], [Link] ID : 010
for child in root: x :2
print([Link], [Link])
📤 Output Example:country {'name': 'Singapore'} A parser is a program or component that:
🔍 Reads structured data (like JSON, XML, or programming Method /
Category Description Example Code Snipp
languages) Function
🛠️Analyzes its structure based on grammar or rules Moves file
📦 Converts it into a usable format (like Python objects) Change File seek(offset, pointer to
[Link](5, 0)
PDF: Pointer whence) specified
Method / Function Description Output Type location
PdfReader Automatically
PdfReader("[Link]") Load the PDF file With opens and
object with open(...) as f: with open("[Link]") as f
All the pages in the List of Statement closes file
[Link] safely
PDF PageObject
len([Link]) Total number of pages int Handles errors
Error try...except try: f=open(...) except
[Link][0] Access a specific page PageObject in file
Handling IOError IOError:
operations
Extract text from the
page.extract_text() str File [Link], [Link], Gives file
page print([Link])
Attributes [Link] metadata
for page in
Loop over every page - Lists all files
[Link]
List and
Combine all page text [Link](path) [Link]('.')
"\n".join(list) str Directory directories in
into a single string
a path
def func(pdf_path):
Gets current
pdf=PdfReader(pdf_path) Get Current [Link]() or
working [Link]([Link]
full_text=[] Path [Link](...)
directory
for page in [Link]:
text=page.extract_text() Filters only
Filter .txt [f for f in files if
full_text.append(text) [Link](".txt") text files in
Files [Link](".txt")]
return "/n".join(full_text) directory
print(func("/content/numpy & [Link]")) Read Loop through .txt Reads all .txt for file in fn: open(file,
📋 Python File I/O Methods – Summary Table Multiple .txt files files into a list 'rb').read()
Method / Write and Read a File
Category Description Example Code Snippet
f = open("[Link]", "w")
Function
[Link]("Python is a Programming Language!!!")
Opens a file in
[Link]()
open(filename, the specified
Open a File f = open("[Link]", "r")
mode) mode (r, w, a,
f = open("[Link]", "r")
rb, wb, etc.)
print([Link]())
Writes string [Link]()
to the file
Write Text write(string) [Link]("Hello!") Seek and Tell
(overwrites in f = open("[Link]", "r")
write mode) [Link](5, 0)
Write Writes a list print([Link](10)) # Reads 10 characters from 5th position
[Link](["Python\n",
Multiple writelines(list) of strings to Binary File Write and Read
"Java\n"])
Lines the file # Writing
Reads the full f = open("[Link]", "wb")
Read Entire
read() content of a content = [Link]() [Link](bytearray([5, 10, 15, 20, 25]))
File
file [Link]()
Reads n
Read Fixed
read(n) characters [Link](10) # Reading
Characters
from the file f = open("[Link]", "rb")
Reads a single print([Link]())
Read Line-
readline() line from the line = [Link]() ✅ os Module Functions Used in the PDF
by-Line
file Function Purpose Example from PDF
Read All Reads all lines Returns the
readlines() lines = [Link]()
Lines as a list absolute
Appends text [Link](path) path of the [Link]([Link]())
Append to Open file in 'a' with open("[Link]", "a") as
to the end of given
File mode f: [Link]("Added text")
the file directory
Binary open(..., 'wb') + Writes binary [Link](bytearray([10, 20, Returns the
Write write(bytearray) data to a file 30])) current path =
[Link]()
Reads binary working [Link]([Link]())
open(..., 'rb') + directory
Binary Read data from a data = [Link]()
read()
file [Link](path) or Lists all [Link](path) or [Link]()
Returns [Link]() files and
File Pointer current directories
tell() pos = [Link]() in the
Position position of
file pointer specified
Function Purpose Example from PDF
path

📌 Code Examples from PDF:


import os

# Get absolute path of current working directory


path = [Link]([Link]())
print(path)

# List files and directories


dir_list = [Link](path)
print("Files and directories in '", path, "' :")
print(dir_list)

📂 Filtering .txt Files from Current Directory:


import os

fn = []
for x in [Link]():
if [Link](".txt"):
[Link](x)
print(fn)

You might also like