The goal of PythonUniverse is to collect and organize Python skills in one place. We've collected some Python techniques, Python modules, and some libraries for data science. Each Topic includes code snippet and further explanation.
Repo windsuzu/PythonUniverse, read from GitHub 13 h ago. windsuzu has not joined Take My Repo.
windsuzu/PythonUniverse is a public repo on GitHub by windsuzu. The goal of PythonUniverse is to collect and organize Python skills in one place. We've collected some Python techniques, Python modules, and some libraries for data science. Each Topic includes code snippet and further explanation. It declares the MIT license on GitHub. It is written mainly in Jupyter Notebook, has 4 stars and last changed on 2021-09-21. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-20.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
| Must Know | Classes | Functions |
|---|---|---|
| Collections | Itertools | Functools |
|---|---|---|
| String | Int | Set | Tuple |
|---|---|---|---|
| Conditional | For-Loop | Try-Except | Design | Ipython |
|---|---|---|---|---|
| Built-ins |
|---|
| Numpy | Pandas | Matplotlib (Pyplot) |
|---|---|---|
| Seaborn |
|---|
[(i, j) for i in range(3) for j in range(3) if i > j] # [(1, 0), (2, 0), (2, 1)]
li = [1, 2, 3] li = [*map(lambda x: x * 10, li)] #li = [10, 20, 30]
num1 = [100, 1, 20] num2 = [19, 4, 94] num3 = [40, 6, 30] [*map(lambda x, y, z: max(x, y, z), num1, num2, num3)] # [100, 6, 94]
names = ['Liam', 'Olivia', 'Noah', 'Emma', 'Oliver', 'Ava'] choice = filter(lambda x: x.startswith('O'), names) print(*choice, sep=', ') # Olivia, Oliver
a = [1, 2, 3] b = [4, 5, 6] c = [*zip(a, b)] # [(1, 4), (2, 5), (3, 6)] a, b = zip(*c) # a=(1, 2, 3), b=(4, 5, 6)
def example(a, *arg, b=0, **kwarg): print(a) # 1 print(arg) # (2, 3) print(b) # 1 print(kwarg) # {'x': 'a', 'y': [1, 2, 3]} example(1, 2, 3, b=1, x='a', y=[1, 2, 3])
def func(greet, time, name): print(greet, time, name) func(*["Good", "Morning"], **{"name": "Jay"}) # Good Morning Jay
a, b, *_ = [1, 2, 3, 4, 5] # 1, 2, [3, 4, 5]
first, *amid, last = map(lambda x: x**2, range(1, 10000)) first # 1 last # 99980001
sales = [("Pencil", 0.22, 1500), ("Notebook", 1.30, 550)] for product, *_ in sales: print(product) # Pencil, Notebook
def compute(i): return i, i ** 2, i ** 3, i ** 4, i ** 5 num, power, cube, *_ = compute(3) power # 9 cube # 27
number = {"one": 1, "two": 2} letter = {"a": "A", "b": "B"} combine = {**number, **letter} combine # {'one': 1, 'two': 2, 'a': 'A', 'b': 'B'}
def square_it(value): for i in range(value): yield i**2 li = square_it(10_000_000) [i for i in li if i < 50] # [0, 1, 4, 9, 16, 25, 36, 49]
def count_decorator(count): # new decorator with argument def decorator(orig_func): def wrapper(*args, **kwargs): print(f"func name: {orig_func.__name__}") print(f"func args: {args}, {kwargs}") for _ in range(count): # use the argument orig_func(*args, **kwargs) return wrapper return decorator # return the original decorator @count_decorator(2) def greet(msg): print(msg) greet("hello") # func name: greet # func args: ('hello',), {} # hello # hello
@contextmanager def enterFolder(folderName): home = os.getcwd() os.chdir(folderName) yield os.chdir(home) with enterFolder('folder1'), open('example1.txt', 'w') as f: f.write('file1')
class BinaryInt(str): def __new__(cls, val): return str.__new__(cls, f"{val: b}") def __add__(self, val): val += int(self, 2) return f"{val:b}" a = BinaryInt(2) print(a) # 10 print(a + 4) # 110
class Meta(type): def __new__(mtcls, name, bases, attrs): if name != "Base" and "must_to_do" not in attrs: raise TypeError("Bad Class: must_to_do() is needed") return super().__new__(mtcls, name, bases, attrs) class Base(metaclass=Meta): def server_func(self): return self.must_to_do() class Derived(Base): ... # TypeError: Bad Class: must_to_do() is needed
import concurrent.futures with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(load_url, url, 60) for url in URLS] for future in concurrent.futures.as_completed(futures): result = future.result() print(len(result)) with concurrent.futures.ProcessPoolExecutor() as executor: results = executor.map(load_url, URLS, [60] * len(URLS), chunksize=4) for result in results: print(len(result))
class Person: def __init__(self, name): self.name = name def say(self): return f"I'm {self.name}" p = Person("Jay") p.say() == Person.say(p) # True
class Employee: num_emp = 0 # Class variable def __init__(self, pay): self.pay = pay # Instance variable Employee.num_emp += 1 e1 = Employee(100) e2 = Employee(200) e1.num_emp # 2 Employee.num_emp # 2 e1.pay # 100 Employee.pay # AttributeError: type object 'Employee' has no attribute 'pay'
class Person: def __init__(self, name, age): self.name = name self.age = age @staticmethod def splitPersonString(string, split_sign="-"): return string.split(split_sign) @classmethod def fromString(cls, cls_str): return cls(*cls.splitPersonString(cls_str, ", ")) p1 = Person.fromString("Jay, 99") p1.name # Jay p1.age # 99
class Dog: _weight = 5 # private variable def __bark(self): # name mangling fucntion print("bark") dog = Dog() dog._weight # 5 dog.__bark() # AttributeError: 'Dog' object has no attribute '__bark' dog._Dog__bark() # bark
class User: def __init__(self, first_name, last_name, password): self.first_name = first_name self.last_name = last_name self.password = password @property def fullname(self): return f"{self.first_name} {self.last_name}" @property def password(self): raise AttributeError("password is not readable.") @password.setter def password(self, passord): from hashlib import md5 self.password_hash = md5(b"{password}").hexdigest() user = User("Mimi", "Wang", "0000") user.fullname # Mimi Wang user.password_hash # 7fbccc9c3a9a5afef65563cd00404c1416 user.password # Attribute Error: password is not readable.
min([1, 2, 31]) # builtins min min = "global min" def outer(): # we can do "global min" here to change global min = "enclosing min" def inner(): # we can do "nonlocal min" here to change enclosing min = "local min"
from abc import ABC, abstractmethod class Base(ABC, object): @property @abstractmethod def foo(self): ... @abstractmethod def do(self): ...
from dataclasses import InitVar, dataclass, field from typing import List @dataclass class InventoryItem: name: str unit_price: float = field(default=0.0) quantity_on_hand: int = field(default=0, repr=False) parts: List[str] = field(default_factory=list) parts_number: InitVar[int] = 0 def __post_init__(self, parts_number): self.parts.extend([f"part{i}" for i in range(1, parts_number + 1)]) item = InventoryItem("product", parts_number=2) # InventoryItem (name = 'product', unit_price=0.0, parts=['part1', 'part2'])
def getClass(x): if x == 1: for i in range(11): class Example: a = i return Example cls = getClass(1) cls.b = "123" print(cls.a, cls.b) # 10 123
def add_with_b(b): def add(a): return a + b return add add4 = add_with_b(4) add4(3) # 7 add4(7) # 11
class Cat: def __repr__(self): return f"({self.name}: {self.age})" listOfCats = [] attrs = [{"name": "meow1", "age": 5}, {"name": "meow2", "age": 10}] for attr in attrs: cat = Cat() for key, val in attr.items(): setattr(cat, key, val) listOfCats.append(cat) print(listOfCats) # [(meow1: 5), (meow2: 10)]
for i in range(100): def say(): print(i) def returnFunc(a): if a < 100: def mul(b): print(a * b) return mul else: def add(b): print(a + b) return add
from collections import defaultdict d = defaultdict(list) d["a"] = [1, 2, 3] d["b"].append(4) d["c"].extend([5, 6]) # defaultdict(<class 'list'>, {'a': [1, 2, 3], 'b': [4], 'c': [5, 6]})
from collections import OrderedDict location = ["C", "B", "A"] population = [32, 46, 12] d = OrderedDict({l: p for l, p in zip(location, population)}) # OrderedDict([('C', 32), ('B', 46), ('A', 12)]) d["D"] = 44 # OrderedDict([('C', 32), ('B', 46), ('A', 12), ('D', 44)]) d.popitem(last=False) # OrderedDict([('B', 46), ('A', 12), ('D', 44)]) d.move_to_end("D", last=False) # OrderedDict ([( 'D', 44), ('B', 46), ('A', 12)])
from collections import Counter c = Counter(cats=4, dogs=8) # Counter({'dogs': 8, 'cats': 4}) c.update(birds=10) # Counter({'birds': 10, 'dogs': 8, 'cats': 4}) c = c - Counter({"birds": 5}) # Counter({'dogs': 8, 'birds': 5, 'cats': 4}) c.most_common(2) # [('dogs', 8), ('birds', 5)]
from collections import namedtuple Dog = namedtuple("Dog", "name, age") d1 = Dog("funny", 4) features = ["happy", 3] d2 = Dog._make(features) # Dog(name='happy', age=3) d2._asdict() # OrderedDict([('name', 'happy'), ('age', 3)])
from collections import deque li = [40, 30, 50, 46, 39, 44] d = deque(li[:2]) # Let 's compute the moving average with range=3 d.appendleft(0) s = sum(d) for elem in li[2:]: s += elem - d.popleft() d.append(elem) print(s / 3) # 40, 42, 45, 43
from itertools import count gen = count(2.5, 0.5) for x in gen: print(x) # 2.5, 3.0, 3.5, 4.0, ... non-stop
from itertools import cycle gen = cycle([1, 2, 3]) for x in gen: print(x) # 1, 2, 3, 1, 2, ... non-stop
from itertools import repeat class Cat: ... gen = repeat(Cat(), 2) for cat in gen: print(cat) # <__main__.Cat object at 0x0000019AC1C5D348> # <__main__.Cat object at 0x0000019AC1C5D348>
import operator from itertools import accumulate gen = accumulate([1, 2, 3, 4]) list(gen) # [1, 3, 6, 10] gen = accumulate([1, 2, 3, 4], func=operator.mul) list(gen) # [1, 2, 6, 24]
from itertools import chain gen = chain([1, 2], [3, 4]) list(gen) # [1, 2, 3, 4] gen = chain("AB", "CD") list(gen) # [A, B, C, D]
from itertools import compress gen = compress([1, 2, 3], [1, 0, 1]) gen = compress([1, 2, 3], [True, False, True]) # same list(gen) # [1, 3]
from itertools import filterfalse gen = filterfalse(lambda x: x%2 == 0, [1, 2, 3]) list(gen) # [1, 3]
from itertools import groupby gen = groupby("AABBCCCAA") # default func = lambda x: x for k, g in gen: print(k, list(g)) # A [A, A] # B [B, B] # C [C, C, C] # A [A, A] gen = groupby([1, 2, 3, 4], lambda x: x // 3) for k, g in gen: print(k, list(g)) # 0 [1, 2] # 1 [3, 4] gen = groupby([("A", 100), ("B", 200), ("C", 600)], lambda x: x[1] > 500) for k, g in gen: print(k, list(g)) # False [(A, 100), (B, 200)] # True [(C, 600)]
gen = islice([1, 2, 3], 2) # equals to A[:2] list(gen) # [1, 2] gen = islice("ABCD", 2, 4) # equals to A[2:4] list(gen) # [C, D] gen = islice("ABCD", 0, None, 2) # equals to A[::2] list(gen) # [A, C]
from itertools import starmap # with only one argument gen = starmap(lambda x: x.lower(), "ABCD") list(gen) # [a, b, c, d] # with 2 arguments gen = starmap(lambda x, y: x + y, [(1, 2), (3, 4)]) list(gen) # [3, 7] # with different size of arugments gen = starmap(lambda *keys: sum(keys) / len(keys), [[3, 8, 3], [4, 2]]) list(gen) # [4.6666667, 3.0]
from itertools import takewhile gen = takewhile(lambda x: x < 2, [1, 2, 3, 2, 1]) list(gen) # [1] gen = takewhile(lambda x: x.isupper(), "ABCdefgHIJ") list(gen) # [A, B, C]
gen = dropwhile(lambda x: x < 2, [1, 2, 3, 2, 1]) list(gen) # [2, 3, 2, 1] gen = dropwhile(lambda x: x.isupper(), "ABCdefgHIJ") list(gen) # [d, e, f, g, H, I, J]
from itertools import zip_longest gen = zip_longest("ABC", ("X", "Y")) list(gen) # [('A', 'X'), ('B', 'Y'), ('C', None)] gen = zip_longest("ABC", [1, 2], fillvalue=-1) list(gen) # [('A', 1), ('B', 2), ('C', -1)]
from itertools import product gen = product("AB", "CD") list(gen) # [AC, AD, BC, BD] gen = product("AB", repeat=2) list(gen) # [AA, AB, BA, BB] gen = product("AB", "CD", repeat=2) list(gen) # [ACAC, ACAD, ACBC, ACBD, # ADAC, ADAD, ADBC, ADBD, # BCAC, BCAD, BCBC, BCBD, # BDAC, BDAD, BDBC, BDBD]
gen = permutations("ABC") # same as r=3 list(gen) # [ABC, ACB, BAC, BCA, CAB, CBA] gen = permutations("ABC", r=2) list(gen) # [AB, AC, BA, BC, CA, CB] gen = permutations("ABC", r=1) list(gen) # [A, B, C]
gen = combinations("ABC", 1) list(gen) # [A, B, C] gen = combinations("ABC", 2) list(gen) # [AB, AC, BC] gen = combinations("ABC", 3) list(gen) # [ABC]
gen = combinations_with_replacement("ABC", 1) list(gen) # [A, B, C] gen = combinations_with_replacement("ABC", 2) list(gen) # [AA, AB, AC, # BB, BC, # CC] gen = combinations_with_replacement("ABC", 3) list(gen) # [AAA, AAB, AAC, ABB, ABC, ACC, # BBB, BBC, BCC, # CCC]
from functools import reduce reduce(lambda x, y: x - y, [1, 2, 3, 4, 5], 100) # 85
first_name = "Kain" last_name = "Mccarthy" print(f"Hi, I'm {first_name} {last_name}.") # Hi, I'm Kain Mccarthy. pi = 3.14159265359 print(f"{pi:.2f}") # 3.14 d = {"name": "Shelly"} print(f"She is {d['name']}") # She is Shelly i = 1000000 print(f"{i:,}") # 1,000,000 # Ref: # * https://youtu.be/nghuHvKLhJA # * https://blog.louie.lu/2017/08/08/outdate-python-string-format-and-fstring/
a = 100_000_000 b = 10_000_000 c = 1_0_0 print(f"{a+b+c:,}") # 110,000,100 # Ref: # * https://youtu.be/C-gEQdGVXbk&t=140
long_list = [i for i in range(100_000_000)] long_set = set(long_list) %%time 100_000_000 in long_list # False # Wall time: 1.26 s %%time 100_000_000 in long_set # False # Wall time: 0 ns # Ref: # * https://stackoverflow.com/questions/2831212/python-sets-vs-lists/17945009 # * https://youtu.be/r3R3h5ly_8g?t=1010
a, b = 1, 2 a # 1 b # 2 a, b = b, a a # 2 b # 1 # Ref: # * https://youtu.be/VBokjWj_cEA?list=LL&t=445
if x < 1: x += 1 else: x -= 1 # equivalent to: x = (x + 1) if (x < 1) else (x - 1) # Ref: # * https://www.youtube.com/watch?v=C-gEQdGVXbk&t=34s
arr = ["a", "b", "c"] for index, element in enumerate(arr): print(index, element) # 0 a # 1 b # 2 c for index, element in enumerate(arr, start=3): print(index, element) # 3 a # 4 b # 5 c # Ref # * https://youtu.be/VBokjWj_cEA?list=LL&t=190
for text in "to be or not to be".split(): if text.strip().startswith("o"): print(f"Found it! `{text}`") break else: print("Not found") # Found it! `or` # Ref: # * https://www.youtube.com/watch?v=Dh-0lAyc3Bc
try: print(1/1) except Exception as e: print(e) else: print("Safe") # executed when except didn't happen finally: print("Done") # Always executed # 1.0 # Safe # Done # Ref: # * https://youtu.be/VBokjWj_cEA?list=LL&t=1331
def func(a: str, b: int = 3) -> str: return a*b func.__annotations__ # {'a': <class 'str'>, 'b': <class 'int'>, 'return': <class 'str'>} func("hi") # hihihi func("hi", 5) # hihihihihi
def func(a: "str longer than 5", b: 1+2 = 3) -> "str longer b times": return a*b func.__annotations__ # {'a': 'str longer than 5', 'b': 3, 'return': 'str longer b times'} func("hi") # hihihi func("ohayou", 2) # ohayouohayou
from typing import Any, Dict, Iterable, List, Union def func(a: List[int], b: Union[str, int], c: Dict[str, int], d: Iterable, e: Any): print(len(a)) print(f"{b} can be str or int.") print(f"{c['something']} will return int.") for i in d: print(i) print(f"{type(e)} can be any type.") # Ref: # * https://myapollo.com.tw/zh-tw/python-typing-module/
# Style 1 def my_abstract_method(self): pass # Style 2 def my_abstract_method(self): ... # Style 3 def my_abstract_method(self): """ This function is ... """ # Ref: # * https://stackoverflow.com/questions/55274977/when-is-the-usage-of-the-python-ellipsis-to-be-preferred-over-pass # * https://stackoverflow.com/questions/772124/what-does-the-ellipsis-object-do
#%% 1+1 # 2 # Ref: # * https://code.visualstudio.com/docs/python/jupyter-support-py
%time sleep(0.3) # Wall time: 310 ms %timeit sleep(0.3) # 311 ms ± 2.06 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%time for i in range(10): sleep(0.1) # Wall time: 1.09 s %%timeit for i in range(10): sleep(0.1) # 1.09 s ± 2.07 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
!pip install -U memory_profiler %load_ext memory_profiler
%memit [i for i in range(1000)] # peak memory: 51.31 MiB, increment: 0.36 MiB
%%memit l = [] for x in range(10000): l.append(x*2) # peak memory: 52.76 MiB, increment: 0.70 MiB
sub_folder = Path("subfolder/subfolder") sub_folder.mkdir(parents=True, exist_ok=True) file_ = sub_folder / Path("test.txt") file_.touch() file_.write_text("Hello") file_.read_text() file_.unlink() Path("subfolder/subfolder").rmdir()
np.array([[1, 2], [3, 4], [5, 6]]) # create from list np.zeros((3, 3)) # create filled with 0's np.ones((2, 4, 4)) # create filled with 1's np.empty((5, 2)) # create with speed np.arange(2, 10, 3) # create array from range (start, end, step_size) np.linspace(5, 50, 20) # create a linear space (start, end, num_elements) # create from random generator rng = np.random.default_rng(seed=42) rng.random((2, 4)) rng.normal(3, 2.5, size=(2, 4)) # sample from N(3, 6.25) rng.integers(low=2, high=10, size=(10, 2)) # random integer matrix
np.sort(a, axis=None) np.sort(a, axis=-1)[::-1] a.sort() a[::-1].sort() np.concatenate((a, b), axis=None) np.concatenate((a, b), axis=2)
a = np.arange(5) # [0, 1, 2, 3, 4] b = np.ones(5, dtype=int) # [1, 1, 1, 1, 1] a + b # [1 2 3 4 5] a - b # [-1 0 1 2 3] a ^ 2 # [ 0 1 4 9 16] a * 10 # [ 0 10 20 30 40] a > 2 # [False False False True True] np.sqrt(a) # [0. , 1. , 1.41421356, 1.73205081, 2. ] a*b # [0 1 2 3 4] a@b # 10
A = np.random.default_rng(42).random((2, 4)) # [[0.77395605, 0.43887844, 0.85859792, 0.69736803], # [0.09417735, 0.97562235, 0.7611397 , 0.78606431]]) A.max() # 0.97562235 A.max(axis=0) # [0.77395605, 0.97562235, 0.85859792, 0.78606431] A.max(axis=1) # [0.85859792, 0.97562235] A.mean() # 0.6732255180088094 A.mean(axis=0) # [0.4340667 , 0.7072504 , 0.80986881, 0.74171617] A.mean(axis=1) # [0.69220011, 0.65425093]
# Index and slicing arrays x[1, 3] == x[1][3] y[1:5:2, ::3] # Indexing arrays x[np.array([0, 1, 2, -1, -2])] y[np.array([1, 2, 3]), 1:4:2] y[np.array([1, 2]), np.array([-1, -1])] # Masking arrays x[x>5] x[(x%2==
windsuzu/PythonUniverse is a public repo on GitHub by windsuzu. The goal of PythonUniverse is to collect and organize Python skills in one place. We've collected some Python techniques, Python modules, and some libraries for data science. Each Topic includes code snippet and further explanation.
It declares the MIT license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2021-09-21. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Notion API client SDK, rewritten in Python! (sync + async)

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
12 weeks, 26 lessons, 52 quizzes, classic Machine Learning for all
Bring data to life with SVG, Canvas and HTML. :bar_chart::chart_with_upwards_trend::tada:

This repo implemented the core technology of the self-driving car, including the basic concepts such as path tracking, path planning, SLAM, etc., and deep learning techniques such as computer vision and reinforcement learning. Finally, we practiced with NVIDIA JetBot in both the simulator and the real world.
Flutterpedia aims to collect, record, implement and instruct all sorts of Flutter implementation techniques. It includes animations, utilities, design patterns, etc. Please use it as a toolbox to facilitate your Flutter development.
It is a note of "design pattern " written in Dart that can also be compiled into a Flutter app. We have some principles such as SOLID, DRY before the design pattern. Then, we have 23 patterns divided into 3 categories: Creational, Structural, and Behavioral design patterns.

We use phonetics as a feature to create a joint semantic-phonetic embedding and improve the neural machine translation between Chinese and Japanese. 🥳

Chinese NER problem that needs to capture 18 types of entities in medical conversation text. The process is divided into 4 parts that are encapsulated in high-level abstract classes. We control the workflow in a single Jupyter notebook.
A youtube search clone built with TypeScript, TailwindCSS, React-Router-Dom, React-Infinite-Scroller
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/windsuzu/PythonUniverseTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.