Be a Master at Python Through Some Cool Code Snippets
Combine two lists as a dictionary | dict(zip)
Program
1keys = ['a', 'b', 'c']
2values = [1, 2, 3]
3dictionary = dict(zip(keys, values))
4print(dictionary)
Output
1{'a': 1, 'b': 2, 'c': 3}
Program
1keys = ('name', 'age', 'location')
2values = ('Soumik', 26, 'Bangladesh')
3
4new_dict = dict(zip(keys, values))
5print(new_dict)
Output
1# output
2{'name' : 'Soumik', 'age' : 26, 'location' : 'Bangladesh'}
Create nested directory
Program
1from pathlib import Path
2
3Path("father/child").mkdir(parents=True, exist_ok=True)
We can also the os
module.
1import os
2
3TARGET_DIR = "parent_dir/child_dir"
4if not os.path.exists(TARGET_DIR):
5 os.makedirs(TARGET_DIR)
Slice Strings
Program
1# print the last character of the string
2text = "abcd"
3text[-1]
Output
1'd'
Program
1# print everything but the last character
2text = "abcd"
3text[:-1] # text[0: -1]
Output
1'abc'
Reverse a string using recursion
1def reverse_text(text):
2 # base condition
3 if text == "":
4 return text
5 else:
6 return text[-1] + reverse_text(text[0:-1])
append and extend in Python List
Program
1x = [1, 2, 3]
2x.append([4, 5])
3print (x)
Output
1[1, 2, 3, [4, 5]]
Program
1x = [1, 2, 3]
2x.extend([4, 5])
3print (x)
Output
1[1, 2, 3, 4, 5]
Program
1my_list = ['Python', 'Java']
2my_list.append('Dart')
3print(my_list)
Output
1['Python', 'Java', 'Dart']
Program
1my_list = ['python', 'java']
2another_list = [0, 1, 2, 3]
3my_list.extend(another_list)
4print(my_list)
Output
1['python', 'java', 0, 1, 2, 3]
Flatten a 2D matrix to a 1D matrix
1matrix = [[1,5,9],[10,11,13],[12,13,15]]
2flat_matrix = sum(matrix, [])
output
1[1, 5, 9, 10, 11, 13, 12, 13, 15]
Check any number exists or not in a list
1nums = [3, 4, 5, 6, 7, 8]
2print(4 in nums)
output
1True
Switch case in Python
Unlike every other programming language, Python does not have a switch or case statement.To get around this fact, we use dictionary mapping.
Program
1def numbers_to_strings(argument):
2 # argument: key of a dictionary
3
4 switcher = {
5 0: "zero",
6 1: "one",
7 2: "two",
8 }
9 return switcher.get(argument, "Data not available")
10
11
12if __name__ == "__main__":
13
14 result = numbers_to_strings(1)
15 print(result)
Output
1one
Program
1def numbers_to_strings(argument):
2 switcher = {
3 0: "zero",
4 1: "one",
5 2: "two",
6 }
7 return switcher.get(argument, "Data not available")
8
9
10if __name__ == "__main__":
11
12 result = numbers_to_strings(4)
13 print(result)
Output
1Data not available
Read and Write File
Program
1# read mode only, if the file does not exists, raises I/O error
2
3filename = open("new_file.txt", "a")
Reverse a list
program
1language = ["Python", "Java", "Dart"]
2language.reverse()
3print(language)
Output
1['Dart', 'Java', 'Python']
Merge two lists
Program
1num1 = [4, 5, 6]
2num2 = [5, 6, 7]
3
4result = num1 + num2
5print(result)
Output
1[4, 5, 6, 5, 6, 7]
Find the common items among multiple lists
2D lists:
1edges = [
2 [1,2],
3 [2,3],
4 [4,2]
5]
6
7common_eleme = set.intersection(*map(set, edges))
8
9for item in common_eleme:
10 print(item) # 2
1D lists
1ar1 = [1, 5, 10, 20, 40, 80]
2ar2 = [6, 7, 20, 80, 100]
3ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
4
5# find the common elements in the three arrays
6common_eleme = set.intersection(*map(set, [ar1, ar2, ar3]))
7
8for item in common_eleme:
9 print(item) # 80 20
Generators in Python
The main advantage of generator over a list is that it takes much less memory. The syntax for generators and list comprehensions:
1 L = [1, 2,3,4]
2>>> [x**x for x in L]
3[1, 4, 27, 256]
4>>> (x**x for x in L)
5<generator object <genexpr> at 0x7fa9fb5aac10>
When to use what?
You should use a list if you want to use any of the list methods. For example, the following code won't work:
1def gen():
2 return (something for something in get_some_stuff())
3
4print gen()[:2] # generators don't support indexing or slicing
5print [5,6] + gen() # generators can't be added to lists
Basically, use a generator expression if all you're doing is iterating once.
If you want to store and use the generated results, then you're probably better off with a list comprehension.
Using generators inside functions
Program
1x = sum(i for i in range(10))
2print(x)
Output
145
Transpose a matrix
Program
1x = [[31, 17], [40, 51], [13, 12]]
2print(list(zip(*x)))
Output
1[(31, 40, 13), (17, 51, 12)]
Find the common prefix for a list of strings
Program
1import os
2
3common = os.path.commonprefix(["flower", "flow", "flight"])
4print(common)
Output
1fl
Using map in Python
Program
1def fn_square(number):
2 return number ** 2
3
4
5if __name__ == "__main__":
6 lst = [1, 2, 3, 4]
7 # map(function, a iterable)
8 square = map(fn_square, lst)
9 result = list(square)
10 print(result)
Output
1[1, 4, 9, 16]
Using Lamda
Program
1
2iterable = [1, 2, 3, 4]
3
4square = map(lambda x: x ** 2, iterable)
5result = list(square)
6print(result)
Output
1[1, 4, 9, 16]
Multiple list
Program
1num1 = [4, 5, 6]
2num2 = [5, 6, 7]
3
4summation = map(sum, zip(num1, num2))
5print(list(summation))
Output
1[9, 11, 13]
Add as many lists you want
Program
1def sum_lists(*args):
2 return list(map(sum, zip(*args)))
3
4
5a = [1, 2, 3]
6b = [1, 2, 3]
7c = [2, 3, 4]
8
9result = sum_lists(a, b, c)
10print(result)
Output
1[4, 7, 10]
kwargs in Python
Program
1def information(**data):
2 for key, value in data.items():
3 print(f"{key}: {value}")
4
5 print()
6
7
8if __name__ == "__main__":
9 information(Firstname="Sadman", Lastname="Soumik", Age=26, Phone=1234567890)
10 information(
11 Firstname="John",
12 Lastname="Wood",
13 Email="johnwood@nomail.com",
14 Country="Wakanda",
15 Age=25,
16 Phone=9876543210,
17 )
Output
1Firstname: Sadman
2Lastname: Soumik
3Age: 26
4Phone: 1234567890
5
6Firstname: John
7Lastname: Wood
8Email: johnwood@nomail.com
9Country: Wakanda
10Age: 25
11Phone: 9876543210
Check the memory usage
Program
1import sys
2
3a, b, c, d = "abcde", "xy", 2, 15.06
4print(sys.getsizeof(a))
5print(sys.getsizeof(b))
6print(sys.getsizeof(c))
7print(sys.getsizeof(d))
Check if a file exists
Program
1import os.path
2
3if os.path.isfile(filepath):
4 print("File exists")
Merge two dictionaries
Program
1x = {'a': 1, 'b': 2}
2y = {'b': 3, 'c': 4}
3z = {**x, **y}
4print(z)
Output
1{'a': 1, 'b': 3, 'c': 4}
Make a flat list list out of lists of lists
Program
1import itertools
2
3list_2d = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
4merged = list(itertools.chain(*list_2d))
5print(merged)
Output
1[1, 2, 3, 4, 5, 6, 7, 8, 9]
Program
1# using list comprehension
2
3list_2d = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
4flat_list = [item for sublist in list_2d for item in sublist]
5print(flat_list)
Output
1[1, 2, 3, 4, 5, 6, 7, 8, 9]
Produce reversed list
Program
1for i in range(10, -1, -1):
2 print(i, end=" ")
Output
110 9 8 7 6 5 4 3 2 1 0
Slicing in array
Program
1a[-1] # last item in the array
2a[-2:] # last two items in the array
3a[:-2] # everything except the last two items
4
5a[::-1] # all items in the array, reversed
Find the index of an item in an array using Python
Program
1list = ["Tensorflow", "PyTorch", "Caffe"]
2idx_pytorch = list.index("PyTorch")
3print(idx_pytorch)
Output
11
minimum len/number in a list
1a = [1, 5, 6, 2, 3, 4]
2print(min(a)) # 1
3
4b = ["flower", "flow", "flight"]
5smallest_str = min(b, key=len)
6print(smallest_str) # flow
Iterating over dictionaries using 'for' loops
Program
1d = {"x": 1, "y": 2, "z": 3}
2
3for key, value in d.items():
4 print(key, value)
Output
1x 1
2y 2
3z 3
Sort a dictionary by key in ascending order in Python
Program
1d = {1: "a", 3: "d", 4: "c", 2: "b", 0: "e"}
2
3sorted_dict = sorted(d.items(), key=lambda x: x[0])
4print(dict(sorted_dict))
Output
1{0: 'e', 1: 'a', 2: 'b', 3: 'd', 4: 'c'}
Sort a dictionary by key in descending order in Python
Program
1sorted_dict = sorted(d.items(), key=lambda x: x[0], reverse=True)
2print(dict(sorted_dict))
Output
1{4: 'c', 3: 'd', 2: 'b', 1: 'a', 0: 'e'}
Sort a diction
Sort a dictionary by value in ascending order in Python
Program
1sorted_dict = sorted(d.items(), key=lambda x: x[1])
2print(dict(sorted_dict))
Output
1{1: 'a', 2: 'b', 4: 'c', 3: 'd', 0: 'e'} # sorted by value
Rename all files of a folder in Python
1import os
2
3os.getcwd()
4src_path = "./source_folder/"
5destination_path = "./destination_folder/"
6
7for i, filename in enumerate(os.listdir(src_path)):
8 os.rename(src_path + filename, destination_path + str(i) + ".jpg")
Count distinct elements in a list
Program
1from collections import Counter
2
3words = ["a", "b", "c", "a", "b", "a"]
4
5print(dict(Counter(words)))
6# {'a': 3, 'b': 2, 'c': 1}
7print(list(Counter(words).keys()))
8# ['a', 'b', 'c']
9print(list(Counter(words).values()))
10# [3, 2, 1]
Most frequent element in a list
Program
1from collections import Counter
2
3
4def most_frequent(lst):
5 data = Counter(lst)
6 return data.most_common(1) # returns most frequent 1 element
7
8
9list = [2, 1, 2, 2, 1, 3, 3, 3, 2]
10print(most_frequent(list))
Output
1[(2, 4)] # means, 2 is the most frequent element which appears 4 times.
Program
1from collections import Counter
2
3
4def most_frequent(lst):
5 data = Counter(lst)
6 return data.most_common(2) # returns most frequent 2 elements
7
8
9list = [2, 1, 2, 2, 1, 3, 3, 3, 2]
10print(most_frequent(list))
Output
1[(2, 4), (3, 3)] # 2 -> 4 times; 3 -> 3 times
Program
1from collections import Counter
2
3
4def most_frequent(lst):
5 data = Counter(lst)
6 return data.most_common(1)[0][0] # [0][0] is the first element of a matrix
7
8list = [2, 1, 2, 2, 1, 3, 3, 3, 2]
9print(most_frequent(list))
Output
12
Find the duplicate elements in a list
Program
1from collections import Counter
2
3
4def find_duplicate(values):
5 duplicates = Counter(values) - Counter(set(values))
6 return list(duplicates.keys())
7
8
9if __name__ == "__main__":
10 values = [1, 2, 3, 3, 3, 4, 5, 6, 6, 7]
11 print(find_duplicate(values))
Output
1[3, 6]
range(9, -1, -1)Collections Module
Create a class using namedtuple
Program
1from collections import namedtuple
2
3# create an Employee class
4Employee = namedtuple("Employee", ["name", "position", "level"])
5print(Employee) # <class '__main__.Employee'>
6
7# assign names in the Employee class
8employee_1 = Employee("Mr. Smith", "Software Engineer", "junior")
9print(employee_1)
10# Employee(name='Mr. Smith', position='Software Engineer', level='junior')
11
12print(employee_1.position) # Software Engineer
13print(dict(employee_1._asdict()))
14# {'name': 'Mr. Smith', 'position': 'Software Engineer', 'level': 'junior'}
Create dictionaries using defaultdict
1from collections import defaultdict
2
3employee_record = [
4 ("Kabir", "ML", "level-b"),
5 ("Sunehra", "SDE", "level-b"),
6 ("Smith", "ML", "level-c"),
7 ("William", "HR", "level-c"),
8]
9
10employee_name_by_dept = defaultdict(list)
11print(employee_name_by_dept)
12# defaultdict(<class 'list'>, {})
13
14for name, dept, level in employee_record:
15 employee_name_by_dept[dept].append(name) # dept as key, name as values
16
17print(dict(employee_name_by_dept))
18# {'ML': ['Kabir', 'Smith'], 'SDE': ['Sunehra'], 'HR': ['William']}
Inserting elements in a list
Program
1employee_list = ["Soumik", "Jamie", "Smith"]
2
3# O(n) performance
4employee_list.insert(0, "Sunehra")
5print(employee_list)
Output
1['Sunehra', 'Soumik', 'Jamie', 'Smith']
Program
1from collections import deque
2
3
4employee_list = ["Soumik", "Jamie", "Smith"]
5employee_list_deque = deque(employee_list)
6
7# O(1) time performance
8employee_list_deque.appendleft("Sunehra")
9print(list(employee_list_deque))
Output
1['Sunehra', 'Soumik', 'Jamie', 'Smith']
Note
Although deque
adds entries to the beginning of a sequence more efficiently than a list, deque
does not perform all of its operations more efficiently than a list. For example, accessing a random item in a deque
has O(n)
performance, but accessing a random item in a list has O(1)
performance.
Use deque
when it is important to insert or remove elements from either side of your collection quickly.
Map multiple dictionary
Program
1from collections import ChainMap
2
3salary = {"SDE": 100000, "HR": 80000, "MTO": 60000}
4office_hq = {"Asia": "Singapore", "Europe": "Dublin", "North America": "USA"}
5age_limit = {"SDE": 40, "HR": 50}
6
7employee_info = ChainMap(salary, office_hq, age_limit)
8print(employee_info.maps)
Output
1[
2 {'SDE': 100000, 'HR': 80000, 'MTO': 60000},
3 {'Asia': 'Singapore', 'Europe': 'Dublin', 'North America': 'USA'},
4 {'SDE': 40, 'HR': 50}
5]
Ordered dictionary
1import collections
2
3# remembers the order
4d = collections.OrderedDict()
5d["A"] = 65
6d["C"] = 67
7d["B"] = 66
8d["D"] = 68
9
10for key, value in d.items():
11 print(key, value)
Output
1A 65
2C 67
3B 66
4D 68
Remove space and newlines from strings
Program
1s = " \n\r\n \n abc def \n\r\n \n "
2remove_all = s.strip()
3remove_left = s.lstrip()
4remove_right = s.rstrip()
5
6print(remove_all) # 'abc def'
7print(remove_left) # 'abc def \n\r\n \n '
8print(remove_right) # ' \n\r\n \n abc def'
Limit floats to two decimal places
Program
1a = 13.946
2print("%.2f" % a)
Output
113.95
Program
1x = 13.946
2print(round(x, 2))
Output
113.95
Randomly select an item from an list.
1import random
2
3foo = ['a', 'b', 'c', 'd', 'e']
4print(random.choice(foo))
Create a single string from all the elements in a list
Program
1a = ["Data", "Science", "Expert"]
2full_str = " ".join(a)
3print(full_str)
Output
1Data Science Expert
Program
1a = ["Data", "Science", "Expert"]
2full_str = ", ".join(a)
3print(full_str)
Output
1Data, Science, Expert
List vs Tuple
List | tuple |
---|---|
A strong culture among python communities is to store homogeneous data ins list | Strong culture in python communities Used to store heterogeneous data in tuples. |
example: l = [1, 2, 3, 4, 5] | example: t = (1, a, 3, d, X) |
Mutable: You can always change a list after data assignment. | Immutable: You can't change it after assignment. |
Common operations: append, extend, insert, remove, pop, reverse, count, copy, clear | Methods that add items or remove items are not available with tuple. [count and index] |
Set:
Set is unordered and contains no duplicates, which makes it very useful for math operations like unions and intersections. Whereas, List and Tuples are Ordered, and contains duplicate elements.
yield keyword
yield
is a keyword that is used like return, except the function will return a generator.
Generators do not store all the values in memory, they generate the values on the fly.
Inheritance in Python
Program
1# define the base class
2
3class Person:
4 def __init__(self, first_name, last_name):
5 self.first_name = first_name
6 self.last_name = last_name
7
8 def print_name(self):
9 print(self.first_name, self.last_name)
10
11
12x = Person("Elon", "Musk")
13x.print_name()
Output
1Elon Musk
Program
1# create a subclass (Entrepreneur) that extends base class(Person)
2
3class Entrepreneur(Person):
4 pass
Program
1# Use the Entrepreneur class to create an object,
2# and then execute the print_name method
3
4
5sub_class_var = Entrepreneur("Elon", "Musk")
6sub_class_var.print_name()
Output
1Elon Musk
Program
1# When we add the __init__() function, the subclass will
2# no longer inherit the parent's/base's __init__() function
3
4
5class Entrepreneur(Person):
6 def __init__(self, first_name, last_name):
7 # add properties
1# we can add super() function that will make the child class
2# inherit all the methods and properties from its parent +
3# we can add it's own properties.
4
5
6class Entrepreneur(Person):
7 def __init__(self, first_name, last_name):
8 super().__init__(first_name, last_name)
Program
1class Entrepreneur(Person):
2 def __init__(self, first_name, last_name):
3 super().__init__(first_name, last_name)
4
5 # adding new properties in the subclass
6 self.company_name = "SpaceX"
Polymorphism in Python
Program
1class Vehicle:
2 # Constructor of the class
3 def __init__(self, name):
4 self.name = name
5
6 # Abstract method, defined by convention only
7 def brand(self):
8 raise NotImplementedError("Subclass must implement abstract method")
9
10
11class Car(Vehicle):
12 def brand(self):
13 return f"Car name: {self.name}"
14
15
16class Bike(Vehicle):
17 def brand(self):
18 return f"Bike name: {self.name}"
19
20
21if __name__ == "__main__":
22 vehicles = [Car("BMW"), Car("Audi"), Bike("Bajaj")]
23
24 for vehicle in vehicles:
25 print(vehicle.brand())
Output
1Car name: BMW
2Car name: Audi
3Bike name: Bajaj
Static methods in python
Program
1class MyClass:
2 @staticmethod
3 def the_static_method(x):
4 print(x)
5
6
7MyClass.the_static_method(2) # outputs 2
Description
We can have static method in Python using @staticmethod
decorator. Like other static methods in other languages, we don't need to create class instance to call the static method. We can directly call the static method using the Class name. Static methods are usually used to create utility functions.
Dunder methods/Magic Functions
Program
1class PrintString:
2 def __init__(self, str):
3 self.str = str
4
5
6if __name__ == "__main__":
7 string_1 = PrintString("Dunder Methods")
8 print(string_1)
Output
1<__main__.PrintString object at 0x7fa4c1709190>
2# prints only the memory address of the string object
Program
1class PrintString:
2 def __init__(self, str):
3 self.str = str
4
5 def __repr__(self):
6 return f"String: {self.str}"
7
8
9if __name__ == "__main__":
10 string_1 = PrintString("Dunder Methods")
11 print(string_1)
Output
1String: Dunder Methods
Program
1class PrintString:
2 def __init__(self, str):
3 self.str = str
4
5 def __repr__(self):
6 return f"String: {self.str}"
7
8
9if __name__ == "__main__":
10 string_1 = PrintString("Dunder Methods")
11
12 # try to add another string with it
13 string_2 = string_1 + "Magic Methods"
14 print(string_2)
Output
1Traceback (most recent call last):
2 File "test_code.py", line 12, in <module>
3 string_2 = string_1 + "Magic Methods"
4TypeError: unsupported operand type(s) for +: 'PrintString' and 'str'
Program
1class PrintString:
2 def __init__(self, str):
3 self.str = str
4
5 def __repr__(self):
6 return f"String: {self.str}"
7
8 def __add__(self, other):
9 return self.str + " " + other
10
11
12if __name__ == "__main__":
13 string_1 = PrintString("Dunder Methods")
14 string_2 = string_1 + "Magic Methods"
15 print(string_2)
Output
1Dunder Methods Magic Methods
str
1class Employee:
2 def __init__(self, name, designation):
3 self.name = name
4 self.designation = designation
5
6 def get_name(self):
7 return self.name
8
9 def get_designation(self):
10 return self.designation
11
12 def print_info(self):
13 return f"Name: {self.name}, Position: {self.position}"
14
15
16if __name__ == "__main__":
17 emp_1 = Employee("Jeff Bezos", "CEO")
18 print(emp_1)
Output
1<__main__.Employee object at 0x7f82303b5390>
2# prints memory address
Program
1class Employee:
2 def __init__(self, name, designation):
3 self.name = name
4 self.designation = designation
5
6 def get_name(self):
7 return self.name
8
9 def get_designation(self):
10 return self.designation
11
12 # use only __str__ instead of print_info
13 def __str__(self):
14 return f"Name: {self.name}, Position: {self.designation}"
15
16
17if __name__ == "__main__":
18 emp_1 = Employee("Jeff Bezos", "CEO")
19 print(emp_1)
1Name: Jeff Bezos, Position: CEO # prints the string
Note:
Python has two different ways to convert an object to a string: str()
and repr()
Define __repr__
for objects you write so you and other developers have a reproducible example when using it as you develop. Define __str__
when you need a human readable string representation of it.
Read JSON file
1import json
2
3def load_data(file):
4 intents = json.loads(open(file).read())
5 return intents
6
7json_file = load_data('filename.json')
Common List Operations in Python
append | extend
1x = [1, 2, 3, 4]
2x.append(5)
3print(x) # [1, 2, 3, 4, 5]
4
5y = [6, 7, 8]
6x.extend(y) # y should be iterable, not int/str
7print(x) # [1, 2, 3, 4, 5, 6, 7, 8]
8
9
10x.insert(0, 10) # insert 10, at position 0
11print(x) # [10, 1, 2, 3, 4, 5, 6, 7, 8]
12
13x.insert(len(x), 20) # insert 20 at the end of the list
14print(x) # [10, 1, 2, 3, 4, 5, 6, 7, 8, 20]
reverse
1
2x = [1, 2, 3, 4]
3
4print(x[::-1]) # [4, 3, 2, 1] ; doesn't chnage the original list
5print(x) # [1, 2, 3, 4]
6
7x.reverse()
8print(x) # [4, 3, 2, 1] ; change the original list inplace
count
1x = [1, 2, 3, 4, 1, 1]
2
3print(x.count(1)) # 3
clear
1x = [1, 2, 3, 4, 1, 1]
2x.clear()
3print(x) # []
index
1x = ["a", "b", "c", "d", "e", "f"]
2print(x.index("d")) # 3
Split a list into x amounts
1x = [1,2,3,4,5,6,7,1,2,3,3,3,3,3,3,3,3,3]
2# split the above list into 8 parts
3split_x = [x[i::8] for i in range(8)]
4print(split_x)
output:
1[[1, 2, 3], [2, 3, 3], [3, 3], [4, 3], [5, 3], [6, 3], [7, 3], [1, 3]]
flatten the split_x:
1flat_x = [item for sublist in split_x for item in sublist]
2print(flat_x)
output:
1[1, 2, 3, 2, 3, 3, 3, 3, 4, 3, 5, 3, 6, 3, 7, 3, 1, 3]
Save all items of a list in a line separated text file
1lst = ['Sample text 1', 'sample text 2', 'sample text 3', 'sample text 4']
2
3SAVE_PATH = './my_list.txt'
4
5with open(SAVE_PATH, mode='wt', encoding='utf-8') as myfile:
6 myfile.write('\n'.join(lst))
Take multiple user inputs
Take two int inputs
1a, b = map(int, input().split())
2print(f"a = {a}; b = {b}")
output:
110 20 # user input
2a = 10; b = 20
Input a list of integers
1l = list(map(int, input().split()))
2print(l)
output:
110 20 30 40 # user input
2[10, 20, 30, 40]
Input a list of strings
1l = list(map(str, input().split()))
2print(l)
output:
1apple google facebook # user input
2['apple', 'google', 'facebook']
Create some random numbers
1import random
2
3sample_list = []
4
5for _ in range(100):
6 # create 100 integers in the range of [10, 1000]
7 sample_list.append(random.randint(10, 1000))
Randomly select 10 items from the sample_list
1selected_sample = random.sample(sample_list, 10)
2print(selected_sample)
Sort a dictionary by its value in ascending order
1def sort_dict_by_value(d):
2 return sorted(d.items(), key=lambda x: x[1], reverse=False)
3
4
5if __name__ == "__main__":
6 d = {"a": 1, "b": 2, "c": 3}
7 print(sort_dict_by_value(d))
output
1[('a', 1), ('b', 2), ('c', 3)]
Print colored text in the terminal
1# pip install termcolor
2
3from termcolor import colored, cprint
4
5text = colored('Hello, World!', 'red')
6print(text)
7cprint('Hello, World!', 'red', 'on_yellow')
output
why lists have .append
and sets have .add
.append
means to add to the end, which is accurate and makes sense for lists, but sets have no notion of ordering and hence no beginning or end, so .add
makes more sense for them.
remove duplicates from a list preserving original order?
1>>> items = [1, 2, 0, 1, 3, 2]
2>>> list(dict.fromkeys(items))
3[1, 2, 0, 3]
Disable all warnings
1!pip install shutup
2
3import shutup
4shutup.please()
Author: Sadman Kabir Soumik