Python Crash Notes for Assignments
📘 Python Notes (From Scratch to Solve Assignments)
1. Python Basics & Rules
- Indentation: Python uses spaces/tabs for blocks (no {}).
- Case Sensitive: Var ≠ var.
- Comments:
- Single line: # This is a comment
- Multi-line: ''' This is multi-line '''
- Variables: Dynamic typing (no need to declare type).
x = 10 # int
y = 3.5 # float
name = "Ram" # string
2. Data Types
- Numbers: int, float, complex
- String (str): "Hello", supports slicing
s = "Python"
print(s[0]) # P
print(s[-1]) # n
print(s[2:5]) # tho
- Boolean: True, False
- None: Represents empty / null
3. Operators
- Arithmetic: + - * / % // **
- Comparison: == != > < >= <=
- Logical: and or not
- Membership: in, not in
- Identity: is, is not
4. Lists
- Ordered, mutable (changeable).
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple
print(fruits[-1]) # mango
print(fruits[1:3]) # ['banana', 'mango']
fruits.append("grape")
fruits.remove("apple")
names = ["Alice", "Bob", "Charlie"]
names.sort(reverse=True) # Sorts in descending order
Common Methods: append(), insert(), remove(), pop(), sort(), reverse(),
len(),count()
5. Tuples
- Ordered, immutable.
t = (1, 2, 3, 4)
print(t[0]) # 1
# t[1] = 10 ❌ Not allowed
6. Sets
- Unordered, no duplicates.
s = {1, 2, 3, 3, 4}
print(s) # {1, 2, 3, 4}
s.add(5)
s.remove(2)
Operations: union(|), intersection(&), difference(-)
7. Dictionaries
- Key-Value pairs, mutable.
d = {"Alice": 20, "Bob": 21}
print(d["Alice"]) # 20
d["Charlie"] = 22 # add
del d["Bob"] # delete
Useful methods: .keys(), .values(), .items()
dictionary[new_key] = dictionary[old_key]
8. Strings (Advanced)
s = "hello world"
print(s.upper()) # HELLO WORLD
print(s.lower()) # hello world
print(s.split()) # ['hello', 'world']
print("-".join(["a","b","c"])) # a-b-c
Reversing: s[::-1]
9. Control Flow
If-Else:
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
Loops:
for i in range(5):
print(i)
while age > 0:
age -= 1
Loop helpers: range(start, stop, step), break, continue
10. Functions
def greet(name):
return "Hello " + name
print(greet("Arpita"))
Lambda (anonymous functions):
square = lambda x: x*x
print(square(5)) # 25
11. List Comprehensions
nums = [x for x in range(10) if x % 2 == 0]
print(nums) # [0, 2, 4, 6, 8]
12. Useful Built-ins
- len(), sum(), min(), max(), sorted()
- map(func, list)
- filter(func, list)
- zip(a, b)
13. String / List Algorithms
- Reverse a string: s[::-1]
- Find duplicates:
lst = [1,2,2,3,4,4]
dupes = [x for x in set(lst) if lst.count(x) > 1]
print(dupes) # [2, 4]
- Anagrams:
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
14. Advanced Practice Topics
- Sorting by length:
words = ["hi", "hello", "a"]
print(sorted(words, key=len)) # ['a', 'hi', 'hello']
- Dictionary inversion:
d = {"a":1, "b":2}
inv = {v:k for k,v in d.items()}
- Binary Search (iterative/recursive)
- String mutations (insert, delete, replace, swap)
- CSV parsing (split by ',')
- Unique elements with set
- Matrix problems (islands)
map(function, iterable)
eg –
def double(x):
return x * 2
nums = [10, 20, 30]
result = map(double, nums)
print(list(result)) # [20, 40, 60]
eg-
names = ["arpita", "jaypee", "python"]
result = map(str.upper, names)
print(list(result)) # ['ARPITA', 'JAYPEE', 'PYTHON']
FILTER
def is_even(x):
return x % 2 == 0
nums = [1, 2, 3, 4, 5, 6]
result = filter(is_even, nums)
print(list(result)) # [2, 4, 6]
map() → transforms each element.
filter() → removes elements not satisfying condition.
Both return iterators (must be converted to list() if you want to print).
Concatenation & Replication only apply to → String, List, Tuple
Summary: String, List, Tuple → support indexing by position.
Dictionary → access by key only.
Set, Numbers, Boolean, NoneType → no indexing.
📘 Data Types – Important Points & Functions
Numbers (int, float, complex): Immutable.
Functions: abs(), pow(), round(), int(), float(), complex()
Strings (str): Immutable, ordered.
Functions: len(), upper(), lower(), title(), strip(), replace(), split(), join(), find(), count(),
startswith(), endswith()
Slicing/Reversing: s[::-1]
Lists (list): Ordered, mutable, allows duplicates.
Functions: append(), insert(), remove(), pop(), sort(), reverse(), count(), index(), extend()
Tuples (tuple): Ordered, immutable.
Functions: count(), index()
Sets (set): Unordered, mutable, no duplicates.
Functions: add(), remove(), discard(), pop()
Operations: union(|), intersection(&), difference(-), symmetric difference(^)
Dictionaries (dict): Key-Value pairs, mutable, unique keys.
Functions: get(), keys(), values(), items(), update(), pop(‘key’), del
Boolean (bool): Values: True, False. Often results of comparisons.
NoneType: Only one value: None, represents 'no value'.
MONDAY
list=[1,2,3,4]
ol=[]
for i in range(3,-1,-1):
ol.append(list[i])
print(ol)