Skip to content

Instantly share code, notes, and snippets.

@sreekarun
Last active February 22, 2026 04:17
Show Gist options
  • Select an option

  • Save sreekarun/4d5bf21fe3aa6c0ae844e0b76ee927e5 to your computer and use it in GitHub Desktop.

Select an option

Save sreekarun/4d5bf21fe3aa6c0ae844e0b76ee927e5 to your computer and use it in GitHub Desktop.
Python notes

Test case variables

print(f"input_vars: {input_vars}")
print(f"original_input_vars: {original_input_vars}")
print(f"returned_output_vars: {returned_output_vars}")
print(f"true_output_vars: {true_output_vars}")

Python Dictionary

Dictionaries

Task Method Code Snippet Notes
Dictionary Get for dictionary safe get my_dict = {'a': 1, 'b': 2}
# Key exists:
value_a = my_dict.get('a', 0)
1
# Key does not exist, returns default (0)
value_c = my_dict.get('c', 0)
0
# Key does not exist, returns None by default:
value_d = my_dict.get('d')
None
Dictionary modification Add item mydict['new_key'] = 'value'
Dictionary modification update with multiple mydict.update( {'key':'v', 'key1':'v1'} )
Dictionary Iteration Key-Value Pairs (Tuple) types = [(k, v) for k, v in pois.items()] Output - list of tuples
Dictionary Iteration Key-Value Pairs (List) types = [[k, v] for k, v in pois.items()] Output - list of lists
Dictionary Iteration Key-Value Pairs (List) types = [k:v for k, v in pois.items()] Output - dictionary
Extracting Keys Comprehension types = [k for k, v in pois.items()]
Extracting Keys Simpler Method types = list(pois.keys())
Extracting Values Comprehension types = [v for k, v in pois.items()]
Extracting Values Simpler Method types = list(pois.values())
Unpacking Keys and Values Separately keys, values = zip(*pois.items())
Reverse Dictionary Comprehension reversed_pois = {v: k for k, v in pois.items()} If original dictionary has duplicate values the reversed dictionary will only keep the last key processed for that value
Count Occorurences Count freq word_list = ['dog', 'cat', 'horse', 'dog']
word_counts = Counter(word_list)
print(word_counts)
#Output: Counter({'dog': 2, 'cat': 1, 'horse': 1})

List

Task Method Code Snippet
Reverse a list list reverse new_list = reversed(old_list)
List Append add items list_sample.append(5)
List extend add multiple items list_sample.extend(list2)
List Insert Inserts at a position my_list.insert(1, 'banana')
List Comprehension Nested Loop Syntax [expression for outer in outer_list for inner in outer]
Flattening Lists Flatten nested list flat_list = [item for sublist in lst for item in sublist]
Use Filter Use filter in iteration def is_even(x): # Returns Trueonly ifx is an even integer
return (x % 2) == 0
# Filter a sequence, keeping just the even values:
for val in filter(is_even, [3, 6, 8, 2, 7, 1, 4, 9, 5, 0]):
print(val, end=' ')
Enumerate to get index and value for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
List Remove [ num for num in L if num != x]

Numeric

Task Method Code Snippet Notes
Convert integer to binary use bin bin(10) Returns '0b1010'; the 0b prefix indicates binary. <class 'str'>
Convert integer to binary Format string f"{10:b}" Returns '1010'; removes the 0b prefix automatically.
Convert to Float float float(val)

Bitwise operators

Task Method / Operator Code Snippet Logic / Description
Bitwise Operation Left Shift x << y Returns x with bits shifted left by y places. Same as x * 2**y. New bits on the right are zeros.
Bitwise Operation Right Shift x >> y Returns x with bits shifted right by y places. Same as x // 2**y. New bits on the right are zeros.
Bitwise AND & a & b Sets bit to 1 if both bits are 1.
Bitwise OR | a | b Sets bit to 1 if one of the bits is 1.
Bitwise XOR ^ a ^ b Sets bit to 1 if only one of the bits is 1.
Bitwise NOT ~ ~a Inverts all the bits.

Regular Expression

Task Method / Operator Code Snippet Logic / Description
RegEx Split Split based on pattern re.split(pattern, string, maxsplit=0, flags=0) splits based on the given pattern
RegEx Findall Returns a list based on the pattern re.findall(pattern, string) is ideal when you need to extract all occurrences of a pattern from a text, such as collecting all the numbers, dates, or email addresses in a document.
RegEx Search is useful for general-purpose scanning when you only need the first instance of a pattern, like finding the first email address in a log file.
RegEx Match is best for input validation where the entire string needs to follow a specific starting format, such as checking for a specific file prefix or a country code in a phone number.

Tuples

Task Method / Operator Code Snippet Logic / Description

Strings

Task Method / Operator Code Snippet Logic / Description
Format string with thousand separator Format with specified separator formatted_streams = f'{streams_avg:,}' Formats it with , as separator
Remove white space from string my_string = " Hello World "
trimmed_string = my_string.strip()
String Concatination out_string = f'{string1}{string2}'

Math

Task Method / Operator Code Snippet Logic / Description
Floor Fraction Floor the fraction math.floor(a/b)
Ceil Fraction Ceil a fraction math.ceil(a/b)
Average No built in method ( a + b + c ) / 3
Min import math
min(my_list)
Max import math
max(my_list)

Set

Task Method / Operator Code Snippet Logic / Description
Set Intersection set1.intersection(set2)

references

Bitwise Operators

@sreekarun
Copy link
Author

student_list = [ grade[0] for grade in grades if grade[0] != 'Student']
exams_score_list = [ grade[1:] for grade in grades if grade[0] != 'Student']
exam_topic_list = grades[0][1:]

result = {student: dict(zip(exam_topic_list, [int(s) for s in scores])) 
       for student, scores in zip(student_list, exams_score_list)}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment