anchor
stringlengths
13
118
positive
stringclasses
235 values
Explain make python object hashable with code. with Python 3 (v2)
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
How do I regex replace python?
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Python: Prefix tree Python
class TrieNode: def __init__(self): self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_end...
Tutorial on __slots__ vs __dict__ tutorial Python (v2)
import sys class WithDict: def __init__(self, x, y): self.x, self.y = x, y class WithSlots: __slots__ = ('x', 'y') def __init__(self, x, y): self.x, self.y = x, y print(sys.getsizeof(WithDict(1,2))) # ~48 bytes print(sys.getsizeof(WithSlots(1,2))) # ~32 bytes
When to use What is the best way to python __slots__ memory op Python (v4)
class Point: __slots__ = ('x', 'y') # restrict to only x, y def __init__(self, x, y): self.x = x self.y = y # No __dict__ => saves memory for millions of instances
What is the best way to how to define __repr__ and with Python 3 (v6)
class Point: def __init__(self, x, y): self.x, self.y = x, y def __repr__(self): return f'Point({self.x!r}, {self.y!r})' def __str__(self): return f'({self.x}, {self.y})'
Advanced snippet for function signature type hints python. Python example
from typing import List, Dict, Optional, Tuple def process(items: List[str], config: Dict[str, int]) -> Optional[Tuple[int, str]]: if not items: return None return len(items), items[0]
Python: pytest fixture Python
import pytest def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 @pytest.mark.parametrize('a,b,expected', [(1,2,3),(0,0,0),(-1,1,0)]) def test_add_parametric(a, b, expected): assert add(a, b) == expected
Python code showing What does thread safe counter python look like in (v5)
import threading class SafeCounter: """Thread-safe counter using Lock.""" def __init__(self): self._value = 0 self._lock = threading.Lock() def increment(self): with self._lock: self._value += 1 @property def value(self): return self._value
Practical use of Code example: python map filter reduce example in Python (v4)
from functools import reduce nums = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums)) total = reduce(lambda a, b: a + b, nums)
How do I how to make http request python with Python 3 (v4)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
Explain and show code to find key with maximum val with Python 3 (v6)
scores = {'math': 88, 'physics': 95, 'chemistry': 91} top_subject = max(scores, key=scores.get)
Tutorial on What is the best way to generator.close() python e Python (v9)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Tutorial on I want to understand nested list comprehension pyt Python (v4)
matrix = [[1,2,3],[4,5,6],[7,8,9]] flat = [elem for row in matrix for elem in row]
Demonstrate interactive generator python in 3. Python guide (v3)
def accumulator(): """Generator that receives values via send() and accumulates.""" total = 0 while True: value = yield total if value is None: break total += value
Explain Show me how to functional programming python in . in Python (v9)
from functools import reduce nums = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums)) total = reduce(lambda a, b: a + b, nums)
Python code showing Give me an example of default value dict python. (v10)
from collections import defaultdict # Group words by first letter words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry'] groups = defaultdict(list) for word in words: groups[word[0]].append(word)
Python 3 What is the best way to custom iterator class pyth example code (v7)
class Countdown: def __init__(self, start): self.start = start def __iter__(self): self.current = self.start return self def __next__(self): if self.current <= 0: raise StopIteration self.current -= 1 return self.current + 1
How does Demonstrate collections.deque python tutorial in work? (v9)
from collections import deque dq = deque(maxlen=5) # fixed-size circular buffer for i in range(10): dq.append(i) print(dq) # deque([5, 6, 7, 8, 9], maxlen=5)
How do I generator expression vs list comprehension?
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Demonstrate function wrapper python in Python 3.
from functools import wraps def my_decorator(func): """Simple decorator that prints before and after.""" @wraps(func) def wrapper(*args, **kwargs): print('Before call') result = func(*args, **kwargs) print('After call') return result return wrapper
What is Give me an example of how to make python object ca in Python? (v6)
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
Python snippet: What does resource management python context manag (v10)
class ManagedFile: """Custom context manager for file handling.""" def __init__(self, name, mode): self.name = name self.mode = mode def __enter__(self): self.file = open(self.name, self.mode) return self.file def __exit__(self, exc_type, exc_val, exc_tb): self....
Python 3 use itertools.cycle to loop infinitely over an ite example code
import itertools def cycle_items(items, count): """Cycle repeatedly over items up to count iterations.""" cycler = itertools.cycle(items) return [next(cycler) for _ in range(count)]
Advanced Explain how to send values into a generator python Python example (v5)
def accumulator(): """Generator that receives values via send() and accumulates.""" total = 0 while True: value = yield total if value is None: break total += value
What is the best way to autocomplete data structur with Python 3 (v2)
class TrieNode: def __init__(self): self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_end...
Understanding I want to understand limit iterator output python. in Python (v5)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
How does Explain @dataclass decorator python with code. work? (v10)
from dataclasses import dataclass @dataclass class Employee: name: str department: str salary: float = 50000.0 def raise_salary(self, percent: float): self.salary *= 1 + percent / 100
Code for Demonstrate context manager protocol python in 3. in Python (v7)
class ManagedFile: """Custom context manager for file handling.""" def __init__(self, name, mode): self.name = name self.mode = mode def __enter__(self): self.file = open(self.name, self.mode) return self.file def __exit__(self, exc_type, exc_val, exc_tb): self....
How does Send JSON data HTTP work? (v3)
import requests payload = {'name': 'Alice', 'score': 99} resp = requests.post('https://api.example.com/submit', json=payload, timeout=10) resp.raise_for_status() print(resp.json())
Write a function to demonstrate Show me how to singleton pattern python in .
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
Practical use of Demonstrate __add__ python example in 3. in Python (v10)
class Vector: def __init__(self, x, y): self.x, self.y = x, y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __repr__(self): return f'Vector({self.x}, {self.y})'
Understanding Show me how to switch statement python in . in Python (v10)
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
What does simple context manager using generator l Python guide (v2)
from contextlib import contextmanager @contextmanager def timer(label=''): """Context manager that times a block.""" import time start = time.perf_counter() try: yield finally: elapsed = time.perf_counter() - start print(f'{label}: {elapsed:.4f}s')
When to use I want to understand one liner list transformation Python (v4)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Show me how to auto generate __init__ python in Python.
from dataclasses import dataclass @dataclass class Employee: name: str department: str salary: float = 50000.0 def raise_salary(self, percent: float): self.salary *= 1 + percent / 100
What is How do I python namedtuple example in Python? (v8)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
Python example of Demonstrate create list from loop python comprehen (v8)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
When to use Explain itertools.product python example with code Python (v10)
import itertools def cartesian_product(a, b): """Compute Cartesian product of two iterables.""" return list(itertools.product(a, b))
Common use case of Word frequency Python (v5)
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
Python 3 Example of how to define generic class with TypeVa example code (v5)
from typing import TypeVar, Generic T = TypeVar('T') class Box(Generic[T]): def __init__(self, item: T): self.item = item def get(self) -> T: return self.item
Explain I want to understand any() all() python. in Python (v8)
nums = [2, 4, 6, 8, 10] print(all(n % 2 == 0 for n in nums)) # True - all even print(any(n > 9 for n in nums)) # True - at least one > 9
Code for snippet for binary search algorithm python. in Python (v10)
def binary_search(arr, target): lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (lo + hi) // 2 if arr[mid] == target: return mid elif arr[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1
Beginner guide to DFS iterative tutorial Python (v10)
def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) for neighbor in graph[start]: if neighbor not in visited: dfs(graph, neighbor, visited) return visited
Advanced Can you show how to use threads in python example Python example (v8)
import threading def worker(name): print(f'Thread {name} starting') threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)] for t in threads: t.start() for t in threads: t.join()
Python code showing Write code for destructuring in python match. (v6)
from dataclasses import dataclass @dataclass class Point: x: int y: int def describe(point): match point: case Point(x=0, y=0): return 'Origin' case Point(x=0, y=y): return f'Y-axis at {y}' case Point(x=x, y=0): return f'X-axis at {x}' ca...
Python 3 What is the best way to readable tuple python example code (v7)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
When to use Square root Python (v8)
import math print(math.sqrt(16)) # 4.0 print(math.floor(3.7)) # 3 print(math.ceil(3.2)) # 4 print(math.log(100, 10)) # 2.0 print(math.pi, math.e) # constants print(math.factorial(5)) # 120
What does how to make http request python look like in Python?
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
Practical use of Code example: python lru_cache decorator example in Python (v8)
from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): """Compute nth Fibonacci number using memoization.""" if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)
Practical use of Give me an example of string interpolation python. in Python (v6)
name = 'Alice' age = 30 pi = 3.14159 # Basic print(f'Hello, {name}!') # Expression print(f'In 5 years: {age + 5}') # Format spec print(f'Pi = {pi:.2f}') # Repr print(f'{name!r}')
Beginner guide to : list comprehension example Python (v5)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
What is __init_subclass__ example in Python? (v6)
class Base: _registry = {} def __init_subclass__(cls, kind=None, **kw): super().__init_subclass__(**kw) if kind: Base._registry[kind] = cls class Dog(Base, kind='dog'): pass class Cat(Base, kind='cat'): pass print(Base._registry) # {'dog': Dog, 'cat': Cat}
Advanced snippet for stateful decorator python using class. Python example
class CountCalls: """Class-based decorator that counts function calls.""" def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 return self.func(*args, **kwargs)
Demonstrate numpy array operations python in 3. Python guide (v6)
import numpy as np a = np.array([1, 2, 3, 4, 5]) b = np.arange(5) c = np.zeros((3, 3)) d = np.ones((2, 4)) print(a * 2) # [2 4 6 8 10] print(a.mean()) # 3.0 print(a @ a) # dot product = 55
Python code showing snippet for how to write a decorator in python. (v3)
from functools import wraps def my_decorator(func): """Simple decorator that prints before and after.""" @wraps(func) def wrapper(*args, **kwargs): print('Before call') result = func(*args, **kwargs) print('After call') return result return wrapper
Practical use of Write code for how to read and write files python in Python (v3)
# Read entire file with open('data.txt', 'r', encoding='utf-8') as f: content = f.read() # Write to file with open('output.txt', 'w', encoding='utf-8') as f: f.write('Hello, World!')
Demonstrate trigonometry python in Python 3.
import math print(math.sqrt(16)) # 4.0 print(math.floor(3.7)) # 3 print(math.ceil(3.2)) # 4 print(math.log(100, 10)) # 2.0 print(math.pi, math.e) # constants print(math.factorial(5)) # 120
Python example of Explain functional programming python with code. (v5)
from functools import reduce nums = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums)) total = reduce(lambda a, b: a + b, nums)
Tutorial on What is the best way to os.environ python example Python (v6)
import os from dotenv import load_dotenv load_dotenv() # reads .env file DB_URL = os.environ['DATABASE_URL'] API_KEY = os.getenv('API_KEY', 'default-key')
What is the best way to fastapi tutorial python with Python 3 (v3)
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.get('/items/{item_id}') def get_item(item_id: int): return {'id': item_id} @app.post('/items/') def create_item(item: Item): return item
When to use snippet for loop with index python. Python (v4)
names = ['Alice', 'Bob', 'Carol'] scores = [95, 87, 92] # zip: pair elements for name, score in zip(names, scores): print(f'{name}: {score}') # enumerate: add index for i, name in enumerate(names, start=1): print(f'{i}. {name}')
Code for How do I config from environment python in Python (v10)
import os from dotenv import load_dotenv load_dotenv() # reads .env file DB_URL = os.environ['DATABASE_URL'] API_KEY = os.getenv('API_KEY', 'default-key')
Python code showing How do I quicksort algorithm python (v3)
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right)
Write a function to demonstrate Explain match case with dataclass python with code (v10)
from dataclasses import dataclass @dataclass class Point: x: int y: int def describe(point): match point: case Point(x=0, y=0): return 'Origin' case Point(x=0, y=y): return f'Y-axis at {y}' case Point(x=x, y=0): return f'X-axis at {x}' ca...
Explain create asyncio Task in Python (v7)
import asyncio async def background_work(): await asyncio.sleep(2) print('Done') async def main(): """Create and schedule a background task.""" task = asyncio.create_task(background_work()) print('Task created, doing other work') await task
Code for Load JSON file tutorial in Python (v3)
import json # Deserialize with open('data.json') as f: data = json.load(f) # Serialize with open('output.json', 'w') as f: json.dump(data, f, indent=2) # String operations text = json.dumps({'key': 'value'}) obj = json.loads(text)
Demonstrate what is a decorator in python in 3. with Python 3 (v6)
from functools import wraps def my_decorator(func): """Simple decorator that prints before and after.""" @wraps(func) def wrapper(*args, **kwargs): print('Before call') result = func(*args, **kwargs) print('After call') return result return wrapper
Give me an example of concatenate iterables without copying.
import itertools def chain_all(*iterables): """Chain multiple iterables into one using itertools.""" return list(itertools.chain(*iterables)) # Usage: chain_all([1,2], [3,4], [5]) -> [1,2,3,4,5]
Understanding Matrix to flat list in Python (v2)
matrix = [[1,2,3],[4,5,6],[7,8,9]] flat = [elem for row in matrix for elem in row]
Interface Python abc module tutorial
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self) -> float: ... @abstractmethod def perimeter(self) -> float: ... class Circle(Shape): def __init__(self, r): self.r = r def area(self): import math; return math.pi * self.r**2 def perimeter...
When to use code to memoize function output with functools.lru Python (v2)
from functools import lru_cache @lru_cache(maxsize=128) def slow_fibonacci(n): if n < 2: return n return slow_fibonacci(n - 1) + slow_fibonacci(n - 2)
How does Explain concurrent async tasks python with code. work? (v10)
import asyncio async def main(): """Run tasks concurrently with asyncio.gather.""" results = await asyncio.gather( fetch('http://api1.com'), fetch('http://api2.com'), fetch('http://api3.com'), ) return results
Understanding Show me how to what is a closure in python in . in Python (v8)
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
When to use I want to understand abstract class python. Python (v10)
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self) -> float: ... @abstractmethod def perimeter(self) -> float: ... class Circle(Shape): def __init__(self, r): self.r = r def area(self): import math; return math.pi * self.r**2 def perimeter...
Understanding Plugin registration __init_subclass__ tutorial in Python (v8)
class Base: _registry = {} def __init_subclass__(cls, kind=None, **kw): super().__init_subclass__(**kw) if kind: Base._registry[kind] = cls class Dog(Base, kind='dog'): pass class Cat(Base, kind='cat'): pass print(Base._registry) # {'dog': Dog, 'cat': Cat}
Common use case of What does dataframe operations python look like in Python (v5)
import pandas as pd df = pd.read_csv('data.csv') # Filter high_salary = df[df['salary'] > 100_000] # Group avg_by_dept = df.groupby('department')['salary'].mean() # New column df['bonus'] = df['salary'] * 0.10
Python 3 Write code for permission flags python enum. example code (v2)
from enum import Flag, auto class Permission(Flag): READ = auto() WRITE = auto() EXECUTE = auto() ALL = READ | WRITE | EXECUTE user_perm = Permission.READ | Permission.WRITE print(Permission.READ in user_perm) # True
Practical use of Demonstrate reduce python object memory in 3. in Python (v2)
import sys class WithDict: def __init__(self, x, y): self.x, self.y = x, y class WithSlots: __slots__ = ('x', 'y') def __init__(self, x, y): self.x, self.y = x, y print(sys.getsizeof(WithDict(1,2))) # ~48 bytes print(sys.getsizeof(WithSlots(1,2))) # ~32 bytes
Write a function to demonstrate : Stable sort recursive (v10)
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(l, r): result = [] i = j = 0 while i < len(l) and j < len(r): if l[i] <= r[j]: result.append(...
Python code showing How do I run multiple coroutines concurrently usin (v9)
import asyncio async def fetch_data(id, delay): await asyncio.sleep(delay) return f"Data {id}" async def main(): results = await asyncio.gather(fetch_data(1, 0.2), fetch_data(2, 0.4)) return results
Understanding Demonstrate functional programming python in 3. in Python (v6)
from functools import reduce nums = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums)) total = reduce(lambda a, b: a + b, nums)
Practical use of Give me an example of how to pass arguments to a d in Python (v4)
from functools import wraps def repeat(n): """Decorator factory: repeat function n times.""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for _ in range(n): result = func(*args, **kwargs) return result return wrapper return ...
Tutorial on How do I file handling python tutorial Python (v5)
# Read entire file with open('data.txt', 'r', encoding='utf-8') as f: content = f.read() # Write to file with open('output.txt', 'w', encoding='utf-8') as f: f.write('Hello, World!')
Python snippet: Example of how to implement two pointers two sum s (v6)
def two_sum_sorted(nums, target): i, j = 0, len(nums) - 1 while i < j: s = nums[i] + nums[j] if s == target: return [i, j] elif s < target: i += 1 else: j -= 1 return []
Python 3 Code example: swallow exception python example code (v10)
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
How do I clone list python?
import copy original = [[1, 2, 3], [4, 5, 6]] shallow = copy.copy(original) # nested lists still shared deep = copy.deepcopy(original) # fully independent copy deep[0][0] = 99 print(original[0][0]) # still 1
When to use Can you show string template python example Python (v10)
# str.format msg = 'Hello, {}! You are {} years old.'.format('Alice', 30) # Named placeholders msg2 = '{name} scored {score:.1f}%'.format(name='Bob', score=92.5) # % style msg3 = 'Value: %d, Float: %.2f' % (42, 3.14)
Write a function to demonstrate code to create simple HTTP server using http.serve
import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(('', PORT), Handler) as httpd: print(f'Serving on port {PORT}') httpd.serve_forever()
Python snippet: exception hierarchy example tutorial (v2)
def divide(a, b): try: return a / b except ZeroDivisionError as e: raise ValueError('b cannot be zero') from e except TypeError: raise else: print('Success') finally: print('Always runs')
Tutorial on Explain metaclass __new__ python with code. Python (v2)
class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class Config(metaclass=SingletonMeta): def __init__(self): self.debug = False
Python example of snippet for transform list with map python. (v6)
from functools import reduce nums = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums)) total = reduce(lambda a, b: a + b, nums)
Practical use of define structural protocol for duck typing interfa in Python (v4)
from typing import Protocol class Drawable(Protocol): def draw(self) -> None: ... def render(obj: Drawable): obj.draw()
How How do I word frequency python is implemented in Python (v6)
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
What is Example of how to format and inspect exception sta in Python?
import traceback try: 1 / 0 except ZeroDivisionError: error_msg = traceback.format_exc() print(f"Captured traceback:\n{error_msg}")
Understanding I want to understand make attribute read only pyth in Python (v5)
class Temperature: """Temperature class with Celsius/Fahrenheit via @property.""" def __init__(self, celsius=0): self._celsius = celsius @property def celsius(self): return self._celsius @celsius.setter def celsius(self, value): if value < -273.15: raise Val...
Implement merge sort tutorial Python guide (v10)
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(l, r): result = [] i = j = 0 while i < len(l) and j < len(r): if l[i] <= r[j]: result.append(...
How Show me how to test case python in . is implemented in Python (v5)
import unittest class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(1 + 1, 2) def test_divide_zero(self): with self.assertRaises(ZeroDivisionError): 1 / 0 if __name__ == '__main__': unittest.main()
Python example of Give me an example of any() all() python. (v10)
nums = [2, 4, 6, 8, 10] print(all(n % 2 == 0 for n in nums)) # True - all even print(any(n > 9 for n in nums)) # True - at least one > 9
Tutorial on Show me how to generic function python typing in . Python (v7)
from typing import TypeVar, Generic, List T = TypeVar('T') class Stack(Generic[T]): def __init__(self) -> None: self._items: List[T] = [] def push(self, item: T) -> None: self._items.append(item) def pop(self) -> T: return self._items.pop()