python tricks
https://chatgpt.com/share/9a8a6b0b-e99c-4e1b-917f-699d9f690aa9
1. Swapping Variables
You can swap two variables without needing a temporary variable:
a, b = 5, 10
a, b = b, aNow, a is 10 and b is 5.
2. List Comprehensions
Generate a new list by applying an expression to each item in an existing list:
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]squares will be [1, 4, 9, 16, 25].
3. Multiple Return Values
Functions can return multiple values, which can be unpacked:
def get_coordinates():
return 10, 20
x, y = get_coordinates()Now, x is 10 and y is 20.
4. Dictionary Comprehensions
Create dictionaries in a concise way:
my_dict will be {'a': 1, 'b': 2, 'c': 3}.
5. Using _ as a Throwaway Variable
_ as a Throwaway VariableUse _ for variables you don’t need to use later:
_ indicates that the variable is just a placeholder.
6. Merging Dictionaries
Merge two dictionaries using **:
merged_dict will be {'a': 1, 'b': 3, 'c': 4}.
7. The enumerate() Function
enumerate() FunctionGet both the index and value while iterating over a list:
This will print:
8. Lambda Functions
Use lambda functions for small, anonymous functions:
9. The zip() Function
zip() FunctionCombine two or more lists into tuples:
zipped will be [(1, 'a'), (2, 'b'), (3, 'c')].
10. Set Operations
Use sets to find unique elements and perform set operations like union, intersection, and difference:
Here are 20 more Python tricks that can help you write more efficient and elegant code:
11. Using any() and all()
any() and all()any(): ReturnsTrueif any element in an iterable isTrue.all(): ReturnsTrueif all elements in an iterable areTrue.
12. Chaining Comparison Operators
You can chain comparison operators for cleaner syntax:
13. Inverting a Dictionary
Swap keys and values in a dictionary:
inverted_dict will be {1: 'a', 2: 'b', 3: 'c'}.
14. Ternary Conditional Operator
Use a single line to write if-else conditions:
15. Default Dictionary with collections.defaultdict
collections.defaultdictAvoid KeyError by using defaultdict from the collections module:
my_dict['a'] will be 1, even if 'a' was not initially in the dictionary.
16. Using Counter from collections
Counter from collectionsCount the frequency of elements in an iterable:
word_count will be Counter({'apple': 2, 'banana': 1, 'orange': 1}).
17. Named Tuples with collections.namedtuple
collections.namedtupleCreate a lightweight object-like structure:
18. Flattening a List of Lists
Use a list comprehension to flatten a nested list:
flat_list will be [1, 2, 3, 4, 5, 6, 7, 8].
19. Finding the Most Common Elements
Use Counter to find the most common elements:
most_common will be [(3, 3)], meaning 3 appears 3 times.
20. Using itertools for Infinite Iteration
itertools for Infinite IterationUse itertools.cycle to cycle through an iterable indefinitely:
21. Using itertools for Cartesian Product
itertools for Cartesian ProductGenerate the Cartesian product of two lists:
product will be [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')].
22. Use filter() to Filter a List
filter() to Filter a ListFilter elements based on a condition:
even_numbers will be [2, 4].
23. Use map() for Element-Wise Operations
map() for Element-Wise OperationsApply a function to every item in an iterable:
squares will be [1, 4, 9, 16, 25].
24. Unpacking Function Arguments
Use * and ** to unpack lists and dictionaries into function arguments:
25. List Slicing with Step
You can slice lists with a step:
even_indexed will be [1, 3, 5].
26. Reversing a String
Reverse a string with slicing:
reversed_s will be "olleH".
27. Enumerating with a Start Index
You can start enumeration at a different index:
This will print:
28. Reading a File into a List of Lines
Use readlines() to read a file into a list of lines:
29. Zipping and Unzipping Lists
Use zip() to combine lists and zip(*...) to unzip:
unzipped will be [(1, 2, 3), ('a', 'b', 'c')].
30. Checking the Memory Usage of an Object
Use sys.getsizeof() to check how much memory an object is using:
31. Using get() with Dictionaries
get() with DictionariesUse get() to avoid KeyError and provide a default value:
value will be 0 since 'c' is not in my_dict.
32. Use del to Remove List Items
del to Remove List ItemsDelete items from a list or dictionary using del:
my_list will be [1, 3, 4].
33. Using try/except/else/finally
try/except/else/finallyHandle exceptions with else and finally blocks:
34. Using with for File Operations
with for File OperationsAutomatically close files with with:
35. Shorthand for Conditional List Appending
Append to a list only if a condition is met:
evens will be [2, 4].
36. Counting Unique Elements with set()
set()Use set() to count the number of unique elements:
unique_count will be 5.
37. Sorting a List of Dictionaries
Sort a list of dictionaries by a specific key:
sorted_people will be [{'name': 'Jane', 'age': 25}, {'name': 'John', 'age': 30}].
38. Combining join() with List Comprehension
join() with List ComprehensionUse join() to concatenate strings with a separator:
sentence will be "Hello World".
39. Using heapq for a Heap Queue
heapq for a Heap QueueMaintain a heap queue with the heapq module:
smallest will be 1.
40. Using json Module for Serialization
json Module for SerializationConvert a Python object to JSON and vice versa:
Here are 30 more Python tricks to further enhance your coding skills:
41. Combining map() with lambda for Transformation
map() with lambda for TransformationApply a transformation to each element in a list:
squares will be [1, 4, 9, 16, 25].
42. Using str.format() for String Formatting
str.format() for String FormattingFormat strings using str.format():
greeting will be "Hello, Alice!".
43. Using setdefault() with Dictionaries
setdefault() with DictionariesUse setdefault() to add a key with a default value if it doesn’t exist:
my_dict will be {'a': 1, 'b': 2}.
44. Sorting with sorted() and a Custom Key
sorted() and a Custom KeySort a list with a custom key:
sorted_words will be ['apple', 'cherry', 'banana'].
45. Using timeit to Measure Execution Time
timeit to Measure Execution TimeMeasure the execution time of small code snippets:
46. Using enumerate() to Iterate with Index
enumerate() to Iterate with IndexIterate over a list with both index and value:
47. Swapping Variables Without a Temporary Variable
Swap two variables in one line:
48. Using type() to Check Variable Type
type() to Check Variable TypeCheck the type of a variable:
49. Using reversed() to Reverse an Iterable
reversed() to Reverse an IterableReverse the order of elements in a list or other iterable:
reversed_numbers will be [5, 4, 3, 2, 1].
50. Using reduce() for Cumulative Operations
reduce() for Cumulative OperationsPerform cumulative operations on a list using functools.reduce():
product will be 120.
51. Using zip() to Iterate Over Multiple Lists
zip() to Iterate Over Multiple ListsIterate over two or more lists simultaneously:
52. Checking for Substring with in
inCheck if a substring exists within a string:
53. Using dict() to Create a Dictionary
dict() to Create a DictionaryCreate a dictionary using the dict() function:
54. Using str.zfill() to Pad Strings
str.zfill() to Pad StringsPad a string with leading zeros:
padded_number will be "00042".
55. Using collections.deque for O(1) Append and Pop
collections.deque for O(1) Append and Popcollections.deque is optimized for fast appends and pops:
56. Using __slots__ to Reduce Memory Usage
__slots__ to Reduce Memory UsageReduce memory usage in classes by defining __slots__:
57. Creating a Generator with yield
yieldUse yield to create a generator instead of returning a list:
58. Using random.sample() to Get Random Samples
random.sample() to Get Random SamplesGet a random sample from a list:
59. Flattening a List of Lists with itertools.chain
itertools.chainFlatten a list of lists using itertools.chain:
60. Using with for Resource Management
with for Resource ManagementUse the with statement to manage resources like files:
61. Handling Large Numbers with decimal
decimalUse the decimal module for precise arithmetic with large numbers:
62. Using functools.lru_cache for Caching
functools.lru_cache for CachingCache the results of expensive function calls:
63. Using bisect for Binary Search
bisect for Binary SearchFind the position to insert an element in a sorted list:
64. Using pathlib for Path Manipulation
pathlib for Path ManipulationUse the pathlib module for path operations:
65. Using itertools.groupby() for Grouping Data
itertools.groupby() for Grouping DataGroup data based on a key function:
66. Using dataclasses for Boilerplate Reduction
dataclasses for Boilerplate ReductionUse dataclasses to reduce boilerplate code in classes:
67. Handling Missing Values with try/except
try/exceptHandle missing values gracefully using try/except:
68. Using type() to Dynamically Create Classes
type() to Dynamically Create ClassesDynamically create classes with type():
69. Using str.join() with Generators
str.join() with GeneratorsUse str.join() with generators for memory-efficient string concatenation:
70. Finding the GCD with math.gcd
math.gcdFind the greatest common divisor using math.gcd:
71. Using subprocess to Run Shell Commands
subprocess to Run Shell CommandsRun shell commands with the subprocess module:
72. **Using math.factorial() to Compute Factorials
math.factorial() to Compute Factorials** Compute factorials using math.factorial():
73. Finding the Length of an Iterator with sum()
sum()Use sum() to find the length of an iterator:
74. Using vars() to Convert Object to Dictionary
vars() to Convert Object to DictionaryConvert an object’s __dict__ to a dictionary:
75. Using next() with Default Values
next() with Default ValuesUse next() with a default value to avoid StopIteration:
Here are 20 more Python tricks to enhance your coding:
76. Using defaultdict from collections
defaultdict from collectionsSimplify dictionary initialization with default values:
77. Using Counter from collections for Counting
Counter from collections for CountingCount occurrences of elements in a list:
78. Using slice() for Flexible Slicing
slice() for Flexible SlicingCreate slices with the slice() function:
79. Using getattr() and setattr()
getattr() and setattr()Access and modify object attributes dynamically:
80. Using contextlib for Custom Context Managers
contextlib for Custom Context ManagersCreate custom context managers with contextlib:
81. Using frozenset for Immutable Sets
frozenset for Immutable SetsUse frozenset to create immutable sets:
82. Using itertools.product() for Cartesian Product
itertools.product() for Cartesian ProductGenerate the Cartesian product of iterables:
83. Using itertools.combinations() for Combinations
itertools.combinations() for CombinationsGenerate all possible combinations of elements:
84. Using functools.partial() for Function Currying
functools.partial() for Function CurryingCreate partial functions with fixed arguments:
85. Using collections.namedtuple() for Lightweight Objects
collections.namedtuple() for Lightweight ObjectsDefine simple classes with named fields:
86. Using math.isqrt() for Integer Square Roots
math.isqrt() for Integer Square RootsCompute the integer square root of a number:
87. Using __import__() for Dynamic Imports
__import__() for Dynamic ImportsImport modules dynamically:
88. Using os.path.join() for Platform-Independent Paths
os.path.join() for Platform-Independent PathsJoin paths in a platform-independent way:
89. Using random.choice() to Select Random Elements
random.choice() to Select Random ElementsRandomly select an element from a list:
90. Using itertools.cycle() for Infinite Iteration
itertools.cycle() for Infinite IterationIterate over a sequence indefinitely:
91. Using os.environ for Environment Variables
os.environ for Environment VariablesAccess environment variables:
92. Using string.ascii_letters for Character Ranges
string.ascii_letters for Character RangesAccess ASCII letters:
93. Using functools.wraps() for Decorators
functools.wraps() for DecoratorsPreserve metadata when using decorators:
94. Using collections.abc for Abstract Base Classes
collections.abc for Abstract Base ClassesCheck if an object is an instance of an abstract base class:
95. Using itertools.count() for Infinite Counting
itertools.count() for Infinite CountingCreate an infinite iterator for counting:
96. Using argparse for Command-Line Argument Parsing
argparse for Command-Line Argument ParsingParse command-line arguments:
97. Using contextlib.redirect_stdout() for Redirecting Output
contextlib.redirect_stdout() for Redirecting OutputRedirect standard output temporarily:
98. Using inspect for Introspection
inspect for IntrospectionInspect live objects, including functions and classes:
99. Using datetime for Date and Time Operations
datetime for Date and Time OperationsManipulate and format dates and times:
100. Using functools.reduce() for Accumulation
functools.reduce() for AccumulationAccumulate values with reduce():
Certainly! Here are 50 more Python tricks to boost your skills:
101. Using itertools.permutations() for Permutations
itertools.permutations() for PermutationsGenerate all permutations of a sequence:
102. Using functools.partialmethod() for Partial Methods
functools.partialmethod() for Partial MethodsCreate methods with some arguments fixed:
103. Using inspect.signature() for Function Signatures
inspect.signature() for Function SignaturesRetrieve function signatures:
104. Using functools.cache() for Caching Results
functools.cache() for Caching ResultsCache results with functools.cache() (Python 3.12+):
105. Using itertools.groupby() for Grouping
itertools.groupby() for GroupingGroup data based on a key:
106. Using __doc__ for Docstrings
__doc__ for DocstringsAccess the docstring of functions and classes:
107. Using collections.ChainMap() for Merging Dictionaries
collections.ChainMap() for Merging DictionariesMerge multiple dictionaries:
108. Using type() for Dynamic Class Creation
type() for Dynamic Class CreationCreate classes dynamically:
109. Using os.path.abspath() for Absolute Paths
os.path.abspath() for Absolute PathsConvert a relative path to an absolute path:
110. Using math.prod() for Product of Iterable
math.prod() for Product of IterableCompute the product of an iterable (Python 3.8+):
111. Using time.strftime() for Formatting Time
time.strftime() for Formatting TimeFormat time using strftime:
112. Using tempfile for Temporary Files
tempfile for Temporary FilesCreate and manage temporary files:
113. Using itertools.islice() for Slicing Iterables
itertools.islice() for Slicing IterablesSlice iterables efficiently:
114. Using contextlib.contextmanager() for Context Managers
contextlib.contextmanager() for Context ManagersDefine context managers using contextmanager:
115. Using functools.update_wrapper() for Decorators
functools.update_wrapper() for DecoratorsEnsure metadata is updated in decorators:
116. Using dataclasses.field() for Default Values
dataclasses.field() for Default ValuesSet default values in dataclasses:
117. Using subprocess.run() for Shell Commands
subprocess.run() for Shell CommandsRun shell commands and capture output:
118. Using pickle for Object Serialization
pickle for Object SerializationSerialize and deserialize objects:
119. Using typing.Optional for Optional Types
typing.Optional for Optional TypesSpecify optional types:
120. Using argparse for Command-Line Parsing
argparse for Command-Line ParsingParse command-line arguments with argparse:
121. Using os.environ for Environment Variables
os.environ for Environment VariablesAccess environment variables:
122. Using shutil for File Operations
shutil for File OperationsPerform high-level file operations:
123. Using mmap for Memory-Mapped File Access
mmap for Memory-Mapped File AccessAccess files via memory mapping:
124. Using heapq.nlargest() for Largest Elements
heapq.nlargest() for Largest ElementsGet the largest n elements:
125. Using collections.OrderedDict for Order Preservation
collections.OrderedDict for Order PreservationPreserve the order of dictionary keys (Python 3.6+ dicts are ordered by default):
126. Using str.translate() for String Translation
str.translate() for String TranslationTranslate characters in a string:
127. Using collections.abc for Abstract Base Classes
collections.abc for Abstract Base ClassesCheck if an object is an instance of an abstract base class:
128. Using math.ceil() for Ceiling Function
math.ceil() for Ceiling FunctionRound numbers up to the nearest integer:
129. Using uuid for Unique Identifiers
uuid for Unique IdentifiersGenerate unique identifiers:
130. Using os.path.splitext() for File Extensions
os.path.splitext() for File ExtensionsSplit the filename into name and extension:
131. Using inspect.getmembers() for Object Attributes
inspect.getmembers() for Object AttributesRetrieve all members of an object:
132. Using collections.UserDict for Custom Dictionaries
collections.UserDict for Custom DictionariesCreate custom dictionary-like objects:
133. Using os.path.expanduser() for User Paths
os.path.expanduser() for User PathsExpand ~ to the full user directory path:
134. Using itertools.combinations_with_replacement()
itertools.combinations_with_replacement()Generate combinations with replacement:
135
. Using operator for Functional Programming Use operators as functions:
136. Using timeit for Measuring Execution Time
timeit for Measuring Execution TimeMeasure the execution time of code snippets:
137. Using functools.singledispatch() for Generic Functions
functools.singledispatch() for Generic FunctionsDefine functions that behave differently based on type:
138. Using subprocess.Popen() for Advanced Process Management
subprocess.Popen() for Advanced Process ManagementStart and manage subprocesses:
139. Using collections.deque for Efficient Queues
collections.deque for Efficient QueuesImplement FIFO or LIFO queues:
140. Using getattr() with Dynamic Attributes
getattr() with Dynamic AttributesDynamically access attributes:
141. Using contextlib.ExitStack() for Multiple Context Managers
contextlib.ExitStack() for Multiple Context ManagersManage multiple context managers:
142. Using functools.lru_cache() for Memoization
functools.lru_cache() for MemoizationCache function results:
143. Using logging.basicConfig() for Basic Logging Setup
logging.basicConfig() for Basic Logging SetupConfigure logging settings:
144. Using collections.defaultdict for Automatic Default Values
collections.defaultdict for Automatic Default ValuesAutomatically initialize dictionary values:
145. Using os.path.dirname() for Directory Name
os.path.dirname() for Directory NameGet the directory name from a path:
146. Using itertools.cycle() for Cycling through Iterables
itertools.cycle() for Cycling through IterablesRepeat elements indefinitely:
147. Using collections.Counter for Element Counting
collections.Counter for Element CountingCount element frequencies:
148. Using functools.wraps to Preserve Metadata
functools.wraps to Preserve MetadataPreserve metadata in decorators:
149. Using dataclasses.asdict() for Converting Dataclasses to Dictionaries
dataclasses.asdict() for Converting Dataclasses to DictionariesConvert dataclasses to dictionaries:
150. Using uuid.uuid1() for Time-Based UUIDs
uuid.uuid1() for Time-Based UUIDsGenerate UUID based on the current time:
Here are 50 more Python tricks to further enhance your skills:
151. Using itertools.starmap() for Argument Unpacking
itertools.starmap() for Argument UnpackingApply a function to arguments unpacked from an iterable:
152. Using collections.namedtuple() for Immutable Objects
collections.namedtuple() for Immutable ObjectsCreate simple classes with named fields:
153. Using __slots__ to Save Memory
__slots__ to Save MemoryDefine fixed attributes to save memory:
154. Using bytearray() for Mutable Bytes
bytearray() for Mutable BytesCreate a mutable byte array:
155. Using pathlib.Path for Path Operations
pathlib.Path for Path OperationsWork with filesystem paths using an object-oriented approach:
156. Using collections.ChainMap for Multi-Dict Lookup
collections.ChainMap for Multi-Dict LookupCombine multiple dictionaries:
157. Using traceback.format_exc() for Exception Tracebacks
traceback.format_exc() for Exception TracebacksGet a formatted traceback of an exception:
158. Using dataclasses.replace() for Copying Instances
dataclasses.replace() for Copying InstancesCreate a new instance with some fields replaced:
159. Using ast.literal_eval() for Safe Evaluation
ast.literal_eval() for Safe EvaluationSafely evaluate strings containing Python literals:
160. Using math.comb() for Combinations (Python 3.8+)
math.comb() for Combinations (Python 3.8+)Calculate combinations:
161. Using contextlib.suppress() for Silencing Exceptions
contextlib.suppress() for Silencing ExceptionsSuppress specified exceptions:
162. Using itertools.product() for Cartesian Products
itertools.product() for Cartesian ProductsCompute Cartesian products:
163. Using types.SimpleNamespace for Dynamic Attributes
types.SimpleNamespace for Dynamic AttributesCreate objects with dynamic attributes:
164. Using decimal.Decimal for Precision Arithmetic
decimal.Decimal for Precision ArithmeticPerform precise decimal arithmetic:
165. Using collections.Counter.most_common() for Top Elements
collections.Counter.most_common() for Top ElementsGet the most common elements:
166. Using types.FunctionType for Dynamic Function Creation
types.FunctionType for Dynamic Function CreationCreate functions dynamically:
167. Using os.path.join() for Path Construction
os.path.join() for Path ConstructionConstruct file paths:
168. Using functools.total_ordering() for Ordering Methods
functools.total_ordering() for Ordering MethodsSimplify class ordering methods:
169. Using os.path.basename() for Base Filename
os.path.basename() for Base FilenameExtract the base name of a file:
170. Using collections.defaultdict with Functions
collections.defaultdict with FunctionsInitialize defaultdict with a function:
171. Using inspect.getargspec() for Function Arguments
inspect.getargspec() for Function ArgumentsGet function argument details:
172. Using random.choices() for Random Sampling with Replacement
random.choices() for Random Sampling with ReplacementRandomly sample elements with replacement:
173. Using heapq.heappush() for Priority Queues
heapq.heappush() for Priority QueuesPush elements onto a priority queue:
174. Using warnings.warn() for Warning Messages
warnings.warn() for Warning MessagesIssue warnings:
175. Using os.makedirs() for Creating Directories
os.makedirs() for Creating DirectoriesCreate directories recursively:
176. Using inspect.getmembers() for Inspecting Classes
inspect.getmembers() for Inspecting ClassesList all members of a class:
177. Using textwrap.fill() for Wrapping Text
textwrap.fill() for Wrapping TextWrap text to a specific width:
178. Using collections.abc.Callable for Callable Check
collections.abc.Callable for Callable CheckCheck if an object is callable:
179. Using pickle.HIGHEST_PROTOCOL for Pickle Protocol
pickle.HIGHEST_PROTOCOL for Pickle ProtocolUse the highest protocol for pickling:
180. Using socket.gethostname() for Hostname
socket.gethostname() for HostnameGet the local machine's hostname:
181. Using contextlib.ExitStack() for Multiple Context Managers
contextlib.ExitStack() for Multiple Context ManagersManage multiple context managers efficiently:
182. Using datetime.timedelta for Date Differences
datetime.timedelta for Date DifferencesCompute differences between dates:
183. Using string.Template for String Substitution
string.Template for String SubstitutionPerform string substitutions:
184. Using functools.reduce() for Reducing Iterables
functools.reduce() for Reducing IterablesReduce an iterable to a single value:
185. Using decimal.getcontext() for Decimal Precision
decimal.getcontext() for Decimal PrecisionSet and get decimal precision:
186. Using itertools.combinations() for Combinations
itertools.combinations() for CombinationsGenerate
all possible combinations:
187. Using re.sub() with Functions
re.sub() with FunctionsReplace text using functions:
188. Using os.getenv() for Environment Variables
os.getenv() for Environment VariablesGet environment variable values:
189. Using itertools.islice() for Slicing Iterables
itertools.islice() for Slicing IterablesSlice iterables efficiently:
190. Using binascii.hexlify() for Binary to Hex Conversion
binascii.hexlify() for Binary to Hex ConversionConvert binary data to hexadecimal:
191. Using functools.partial() for Function Specialization
functools.partial() for Function SpecializationCreate a specialized version of a function:
192. Using pickle.load() and pickle.dump() for Serialization
pickle.load() and pickle.dump() for SerializationSerialize and deserialize objects:
193. Using threading.Thread for Concurrency
threading.Thread for ConcurrencyRun code in parallel threads:
194. Using functools.cached_property for Cached Properties
functools.cached_property for Cached PropertiesCache property results:
195. Using uuid.uuid4() for Random UUIDs
uuid.uuid4() for Random UUIDsGenerate a random UUID:
196. Using dataclasses.field() for Field Defaults
dataclasses.field() for Field DefaultsSet default values for dataclass fields:
197. Using io.StringIO for In-Memory Text Streams
io.StringIO for In-Memory Text StreamsCreate an in-memory text stream:
198. Using ctypes for Calling C Functions
ctypes for Calling C FunctionsCall C functions from Python:
199. Using operator.attrgetter() for Attribute Access
operator.attrgetter() for Attribute AccessAccess attributes using a getter function:
200. Using unittest.mock.patch() for Mocking
unittest.mock.patch() for MockingMock objects for testing:
Last updated