python tricks
https://chatgpt.com/share/9a8a6b0b-e99c-4e1b-917f-699d9f690aa9
1. Swapping Variables
a, b = 5, 10
a, b = b, a2. List Comprehensions
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]3. Multiple Return Values
def get_coordinates():
return 10, 20
x, y = get_coordinates()4. Dictionary Comprehensions
5. Using _ as a Throwaway Variable
_ as a Throwaway Variable6. Merging Dictionaries
7. The enumerate() Function
enumerate() Function8. Lambda Functions
9. The zip() Function
zip() Function10. Set Operations
11. Using any() and all()
any() and all()12. Chaining Comparison Operators
13. Inverting a Dictionary
14. Ternary Conditional Operator
15. Default Dictionary with collections.defaultdict
collections.defaultdict16. Using Counter from collections
Counter from collections17. Named Tuples with collections.namedtuple
collections.namedtuple18. Flattening a List of Lists
19. Finding the Most Common Elements
20. Using itertools for Infinite Iteration
itertools for Infinite Iteration21. Using itertools for Cartesian Product
itertools for Cartesian Product22. Use filter() to Filter a List
filter() to Filter a List23. Use map() for Element-Wise Operations
map() for Element-Wise Operations24. Unpacking Function Arguments
25. List Slicing with Step
26. Reversing a String
27. Enumerating with a Start Index
28. Reading a File into a List of Lines
29. Zipping and Unzipping Lists
30. Checking the Memory Usage of an Object
31. Using get() with Dictionaries
get() with Dictionaries32. Use del to Remove List Items
del to Remove List Items33. Using try/except/else/finally
try/except/else/finally34. Using with for File Operations
with for File Operations35. Shorthand for Conditional List Appending
36. Counting Unique Elements with set()
set()37. Sorting a List of Dictionaries
38. Combining join() with List Comprehension
join() with List Comprehension39. Using heapq for a Heap Queue
heapq for a Heap Queue40. Using json Module for Serialization
json Module for Serialization41. Combining map() with lambda for Transformation
map() with lambda for Transformation42. Using str.format() for String Formatting
str.format() for String Formatting43. Using setdefault() with Dictionaries
setdefault() with Dictionaries44. Sorting with sorted() and a Custom Key
sorted() and a Custom Key45. Using timeit to Measure Execution Time
timeit to Measure Execution Time46. Using enumerate() to Iterate with Index
enumerate() to Iterate with Index47. Swapping Variables Without a Temporary Variable
48. Using type() to Check Variable Type
type() to Check Variable Type49. Using reversed() to Reverse an Iterable
reversed() to Reverse an Iterable50. Using reduce() for Cumulative Operations
reduce() for Cumulative Operations51. Using zip() to Iterate Over Multiple Lists
zip() to Iterate Over Multiple Lists52. Checking for Substring with in
in53. Using dict() to Create a Dictionary
dict() to Create a Dictionary54. Using str.zfill() to Pad Strings
str.zfill() to Pad Strings55. Using collections.deque for O(1) Append and Pop
collections.deque for O(1) Append and Pop56. Using __slots__ to Reduce Memory Usage
__slots__ to Reduce Memory Usage57. Creating a Generator with yield
yield58. Using random.sample() to Get Random Samples
random.sample() to Get Random Samples59. Flattening a List of Lists with itertools.chain
itertools.chain60. Using with for Resource Management
with for Resource Management61. Handling Large Numbers with decimal
decimal62. Using functools.lru_cache for Caching
functools.lru_cache for Caching63. Using bisect for Binary Search
bisect for Binary Search64. Using pathlib for Path Manipulation
pathlib for Path Manipulation65. Using itertools.groupby() for Grouping Data
itertools.groupby() for Grouping Data66. Using dataclasses for Boilerplate Reduction
dataclasses for Boilerplate Reduction67. Handling Missing Values with try/except
try/except68. Using type() to Dynamically Create Classes
type() to Dynamically Create Classes69. Using str.join() with Generators
str.join() with Generators70. Finding the GCD with math.gcd
math.gcd71. Using subprocess to Run Shell Commands
subprocess to Run Shell Commands72. **Using math.factorial() to Compute Factorials
math.factorial() to Compute Factorials73. Finding the Length of an Iterator with sum()
sum()74. Using vars() to Convert Object to Dictionary
vars() to Convert Object to Dictionary75. Using next() with Default Values
next() with Default Values76. Using defaultdict from collections
defaultdict from collections77. Using Counter from collections for Counting
Counter from collections for Counting78. Using slice() for Flexible Slicing
slice() for Flexible Slicing79. Using getattr() and setattr()
getattr() and setattr()80. Using contextlib for Custom Context Managers
contextlib for Custom Context Managers81. Using frozenset for Immutable Sets
frozenset for Immutable Sets82. Using itertools.product() for Cartesian Product
itertools.product() for Cartesian Product83. Using itertools.combinations() for Combinations
itertools.combinations() for Combinations84. Using functools.partial() for Function Currying
functools.partial() for Function Currying85. Using collections.namedtuple() for Lightweight Objects
collections.namedtuple() for Lightweight Objects86. Using math.isqrt() for Integer Square Roots
math.isqrt() for Integer Square Roots87. Using __import__() for Dynamic Imports
__import__() for Dynamic Imports88. Using os.path.join() for Platform-Independent Paths
os.path.join() for Platform-Independent Paths89. Using random.choice() to Select Random Elements
random.choice() to Select Random Elements90. Using itertools.cycle() for Infinite Iteration
itertools.cycle() for Infinite Iteration91. Using os.environ for Environment Variables
os.environ for Environment Variables92. Using string.ascii_letters for Character Ranges
string.ascii_letters for Character Ranges93. Using functools.wraps() for Decorators
functools.wraps() for Decorators94. Using collections.abc for Abstract Base Classes
collections.abc for Abstract Base Classes95. Using itertools.count() for Infinite Counting
itertools.count() for Infinite Counting96. Using argparse for Command-Line Argument Parsing
argparse for Command-Line Argument Parsing97. Using contextlib.redirect_stdout() for Redirecting Output
contextlib.redirect_stdout() for Redirecting Output98. Using inspect for Introspection
inspect for Introspection99. Using datetime for Date and Time Operations
datetime for Date and Time Operations100. Using functools.reduce() for Accumulation
functools.reduce() for Accumulation101. Using itertools.permutations() for Permutations
itertools.permutations() for Permutations102. Using functools.partialmethod() for Partial Methods
functools.partialmethod() for Partial Methods103. Using inspect.signature() for Function Signatures
inspect.signature() for Function Signatures104. Using functools.cache() for Caching Results
functools.cache() for Caching Results105. Using itertools.groupby() for Grouping
itertools.groupby() for Grouping106. Using __doc__ for Docstrings
__doc__ for Docstrings107. Using collections.ChainMap() for Merging Dictionaries
collections.ChainMap() for Merging Dictionaries108. Using type() for Dynamic Class Creation
type() for Dynamic Class Creation109. Using os.path.abspath() for Absolute Paths
os.path.abspath() for Absolute Paths110. Using math.prod() for Product of Iterable
math.prod() for Product of Iterable111. Using time.strftime() for Formatting Time
time.strftime() for Formatting Time112. Using tempfile for Temporary Files
tempfile for Temporary Files113. Using itertools.islice() for Slicing Iterables
itertools.islice() for Slicing Iterables114. Using contextlib.contextmanager() for Context Managers
contextlib.contextmanager() for Context Managers115. Using functools.update_wrapper() for Decorators
functools.update_wrapper() for Decorators116. Using dataclasses.field() for Default Values
dataclasses.field() for Default Values117. Using subprocess.run() for Shell Commands
subprocess.run() for Shell Commands118. Using pickle for Object Serialization
pickle for Object Serialization119. Using typing.Optional for Optional Types
typing.Optional for Optional Types120. Using argparse for Command-Line Parsing
argparse for Command-Line Parsing121. Using os.environ for Environment Variables
os.environ for Environment Variables122. Using shutil for File Operations
shutil for File Operations123. Using mmap for Memory-Mapped File Access
mmap for Memory-Mapped File Access124. Using heapq.nlargest() for Largest Elements
heapq.nlargest() for Largest Elements125. Using collections.OrderedDict for Order Preservation
collections.OrderedDict for Order Preservation126. Using str.translate() for String Translation
str.translate() for String Translation127. Using collections.abc for Abstract Base Classes
collections.abc for Abstract Base Classes128. Using math.ceil() for Ceiling Function
math.ceil() for Ceiling Function129. Using uuid for Unique Identifiers
uuid for Unique Identifiers130. Using os.path.splitext() for File Extensions
os.path.splitext() for File Extensions131. Using inspect.getmembers() for Object Attributes
inspect.getmembers() for Object Attributes132. Using collections.UserDict for Custom Dictionaries
collections.UserDict for Custom Dictionaries133. Using os.path.expanduser() for User Paths
os.path.expanduser() for User Paths134. Using itertools.combinations_with_replacement()
itertools.combinations_with_replacement()135
136. Using timeit for Measuring Execution Time
timeit for Measuring Execution Time137. Using functools.singledispatch() for Generic Functions
functools.singledispatch() for Generic Functions138. Using subprocess.Popen() for Advanced Process Management
subprocess.Popen() for Advanced Process Management139. Using collections.deque for Efficient Queues
collections.deque for Efficient Queues140. Using getattr() with Dynamic Attributes
getattr() with Dynamic Attributes141. Using contextlib.ExitStack() for Multiple Context Managers
contextlib.ExitStack() for Multiple Context Managers142. Using functools.lru_cache() for Memoization
functools.lru_cache() for Memoization143. Using logging.basicConfig() for Basic Logging Setup
logging.basicConfig() for Basic Logging Setup144. Using collections.defaultdict for Automatic Default Values
collections.defaultdict for Automatic Default Values145. Using os.path.dirname() for Directory Name
os.path.dirname() for Directory Name146. Using itertools.cycle() for Cycling through Iterables
itertools.cycle() for Cycling through Iterables147. Using collections.Counter for Element Counting
collections.Counter for Element Counting148. Using functools.wraps to Preserve Metadata
functools.wraps to Preserve Metadata149. Using dataclasses.asdict() for Converting Dataclasses to Dictionaries
dataclasses.asdict() for Converting Dataclasses to Dictionaries150. Using uuid.uuid1() for Time-Based UUIDs
uuid.uuid1() for Time-Based UUIDs151. Using itertools.starmap() for Argument Unpacking
itertools.starmap() for Argument Unpacking152. Using collections.namedtuple() for Immutable Objects
collections.namedtuple() for Immutable Objects153. Using __slots__ to Save Memory
__slots__ to Save Memory154. Using bytearray() for Mutable Bytes
bytearray() for Mutable Bytes155. Using pathlib.Path for Path Operations
pathlib.Path for Path Operations156. Using collections.ChainMap for Multi-Dict Lookup
collections.ChainMap for Multi-Dict Lookup157. Using traceback.format_exc() for Exception Tracebacks
traceback.format_exc() for Exception Tracebacks158. Using dataclasses.replace() for Copying Instances
dataclasses.replace() for Copying Instances159. Using ast.literal_eval() for Safe Evaluation
ast.literal_eval() for Safe Evaluation160. Using math.comb() for Combinations (Python 3.8+)
math.comb() for Combinations (Python 3.8+)161. Using contextlib.suppress() for Silencing Exceptions
contextlib.suppress() for Silencing Exceptions162. Using itertools.product() for Cartesian Products
itertools.product() for Cartesian Products163. Using types.SimpleNamespace for Dynamic Attributes
types.SimpleNamespace for Dynamic Attributes164. Using decimal.Decimal for Precision Arithmetic
decimal.Decimal for Precision Arithmetic165. Using collections.Counter.most_common() for Top Elements
collections.Counter.most_common() for Top Elements166. Using types.FunctionType for Dynamic Function Creation
types.FunctionType for Dynamic Function Creation167. Using os.path.join() for Path Construction
os.path.join() for Path Construction168. Using functools.total_ordering() for Ordering Methods
functools.total_ordering() for Ordering Methods169. Using os.path.basename() for Base Filename
os.path.basename() for Base Filename170. Using collections.defaultdict with Functions
collections.defaultdict with Functions171. Using inspect.getargspec() for Function Arguments
inspect.getargspec() for Function Arguments172. Using random.choices() for Random Sampling with Replacement
random.choices() for Random Sampling with Replacement173. Using heapq.heappush() for Priority Queues
heapq.heappush() for Priority Queues174. Using warnings.warn() for Warning Messages
warnings.warn() for Warning Messages175. Using os.makedirs() for Creating Directories
os.makedirs() for Creating Directories176. Using inspect.getmembers() for Inspecting Classes
inspect.getmembers() for Inspecting Classes177. Using textwrap.fill() for Wrapping Text
textwrap.fill() for Wrapping Text178. Using collections.abc.Callable for Callable Check
collections.abc.Callable for Callable Check179. Using pickle.HIGHEST_PROTOCOL for Pickle Protocol
pickle.HIGHEST_PROTOCOL for Pickle Protocol180. Using socket.gethostname() for Hostname
socket.gethostname() for Hostname181. Using contextlib.ExitStack() for Multiple Context Managers
contextlib.ExitStack() for Multiple Context Managers182. Using datetime.timedelta for Date Differences
datetime.timedelta for Date Differences183. Using string.Template for String Substitution
string.Template for String Substitution184. Using functools.reduce() for Reducing Iterables
functools.reduce() for Reducing Iterables185. Using decimal.getcontext() for Decimal Precision
decimal.getcontext() for Decimal Precision186. Using itertools.combinations() for Combinations
itertools.combinations() for Combinations187. Using re.sub() with Functions
re.sub() with Functions188. Using os.getenv() for Environment Variables
os.getenv() for Environment Variables189. Using itertools.islice() for Slicing Iterables
itertools.islice() for Slicing Iterables190. Using binascii.hexlify() for Binary to Hex Conversion
binascii.hexlify() for Binary to Hex Conversion191. Using functools.partial() for Function Specialization
functools.partial() for Function Specialization192. Using pickle.load() and pickle.dump() for Serialization
pickle.load() and pickle.dump() for Serialization193. Using threading.Thread for Concurrency
threading.Thread for Concurrency194. Using functools.cached_property for Cached Properties
functools.cached_property for Cached Properties195. Using uuid.uuid4() for Random UUIDs
uuid.uuid4() for Random UUIDs196. Using dataclasses.field() for Field Defaults
dataclasses.field() for Field Defaults197. Using io.StringIO for In-Memory Text Streams
io.StringIO for In-Memory Text Streams198. Using ctypes for Calling C Functions
ctypes for Calling C Functions199. Using operator.attrgetter() for Attribute Access
operator.attrgetter() for Attribute Access200. Using unittest.mock.patch() for Mocking
unittest.mock.patch() for MockingLast updated