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, a

Now, 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

Use _ 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

Get 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

Combine 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(): Returns True if any element in an iterable is True.

  • all(): Returns True if all elements in an iterable are True.

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

Avoid 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

Count the frequency of elements in an iterable:

word_count will be Counter({'apple': 2, 'banana': 1, 'orange': 1}).

17. Named Tuples with collections.namedtuple

Create 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

Use itertools.cycle to cycle through an iterable indefinitely:

21. Using itertools for Cartesian Product

Generate 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 elements based on a condition:

even_numbers will be [2, 4].

23. Use map() for Element-Wise Operations

Apply 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

Use 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

Delete items from a list or dictionary using del:

my_list will be [1, 3, 4].

33. Using try/except/else/finally

Handle exceptions with else and finally blocks:

34. Using with for File Operations

Automatically 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()

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

Use join() to concatenate strings with a separator:

sentence will be "Hello World".

39. Using heapq for a Heap Queue

Maintain a heap queue with the heapq module:

smallest will be 1.

40. Using json Module for Serialization

Convert 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

Apply a transformation to each element in a list:

squares will be [1, 4, 9, 16, 25].

42. Using str.format() for String Formatting

Format strings using str.format():

greeting will be "Hello, Alice!".

43. Using setdefault() with Dictionaries

Use 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

Sort a list with a custom key:

sorted_words will be ['apple', 'cherry', 'banana'].

45. Using timeit to Measure Execution Time

Measure the execution time of small code snippets:

46. Using enumerate() to Iterate with Index

Iterate 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

Check the type of a variable:

49. Using reversed() to Reverse an Iterable

Reverse 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

Perform cumulative operations on a list using functools.reduce():

product will be 120.

51. Using zip() to Iterate Over Multiple Lists

Iterate over two or more lists simultaneously:

52. Checking for Substring with in

Check if a substring exists within a string:

53. Using dict() to Create a Dictionary

Create a dictionary using the dict() function:

54. Using str.zfill() to Pad Strings

Pad a string with leading zeros:

padded_number will be "00042".

55. Using collections.deque for O(1) Append and Pop

collections.deque is optimized for fast appends and pops:

56. Using __slots__ to Reduce Memory Usage

Reduce memory usage in classes by defining __slots__:

57. Creating a Generator with yield

Use yield to create a generator instead of returning a list:

58. Using random.sample() to Get Random Samples

Get a random sample from a list:

59. Flattening a List of Lists with itertools.chain

Flatten a list of lists using itertools.chain:

60. Using with for Resource Management

Use the with statement to manage resources like files:

61. Handling Large Numbers with decimal

Use the decimal module for precise arithmetic with large numbers:

62. Using functools.lru_cache for Caching

Cache the results of expensive function calls:

Find the position to insert an element in a sorted list:

64. Using pathlib for Path Manipulation

Use the pathlib module for path operations:

65. Using itertools.groupby() for Grouping Data

Group data based on a key function:

66. Using dataclasses for Boilerplate Reduction

Use dataclasses to reduce boilerplate code in classes:

67. Handling Missing Values with try/except

Handle missing values gracefully using try/except:

68. Using type() to Dynamically Create Classes

Dynamically create classes with type():

69. Using str.join() with Generators

Use str.join() with generators for memory-efficient string concatenation:

70. Finding the GCD with math.gcd

Find the greatest common divisor using math.gcd:

71. Using subprocess to Run Shell Commands

Run shell commands with the subprocess module:

72. **Using math.factorial() to Compute Factorials

** Compute factorials using math.factorial():

73. Finding the Length of an Iterator with sum()

Use sum() to find the length of an iterator:

74. Using vars() to Convert Object to Dictionary

Convert an object’s __dict__ to a dictionary:

75. Using next() with Default Values

Use next() with a default value to avoid StopIteration:

Here are 20 more Python tricks to enhance your coding:

76. Using defaultdict from collections

Simplify dictionary initialization with default values:

77. Using Counter from collections for Counting

Count occurrences of elements in a list:

78. Using slice() for Flexible Slicing

Create slices with the slice() function:

79. Using getattr() and setattr()

Access and modify object attributes dynamically:

80. Using contextlib for Custom Context Managers

Create custom context managers with contextlib:

81. Using frozenset for Immutable Sets

Use frozenset to create immutable sets:

82. Using itertools.product() for Cartesian Product

Generate the Cartesian product of iterables:

83. Using itertools.combinations() for Combinations

Generate all possible combinations of elements:

84. Using functools.partial() for Function Currying

Create partial functions with fixed arguments:

85. Using collections.namedtuple() for Lightweight Objects

Define simple classes with named fields:

86. Using math.isqrt() for Integer Square Roots

Compute the integer square root of a number:

87. Using __import__() for Dynamic Imports

Import modules dynamically:

88. Using os.path.join() for Platform-Independent Paths

Join paths in a platform-independent way:

89. Using random.choice() to Select Random Elements

Randomly select an element from a list:

90. Using itertools.cycle() for Infinite Iteration

Iterate over a sequence indefinitely:

91. Using os.environ for Environment Variables

Access environment variables:

92. Using string.ascii_letters for Character Ranges

Access ASCII letters:

93. Using functools.wraps() for Decorators

Preserve metadata when using decorators:

94. Using collections.abc for Abstract Base Classes

Check if an object is an instance of an abstract base class:

95. Using itertools.count() for Infinite Counting

Create an infinite iterator for counting:

96. Using argparse for Command-Line Argument Parsing

Parse command-line arguments:

97. Using contextlib.redirect_stdout() for Redirecting Output

Redirect standard output temporarily:

98. Using inspect for Introspection

Inspect live objects, including functions and classes:

99. Using datetime for Date and Time Operations

Manipulate and format dates and times:

100. Using functools.reduce() for Accumulation

Accumulate values with reduce():

Certainly! Here are 50 more Python tricks to boost your skills:

101. Using itertools.permutations() for Permutations

Generate all permutations of a sequence:

102. Using functools.partialmethod() for Partial Methods

Create methods with some arguments fixed:

103. Using inspect.signature() for Function Signatures

Retrieve function signatures:

104. Using functools.cache() for Caching Results

Cache results with functools.cache() (Python 3.12+):

105. Using itertools.groupby() for Grouping

Group data based on a key:

106. Using __doc__ for Docstrings

Access the docstring of functions and classes:

107. Using collections.ChainMap() for Merging Dictionaries

Merge multiple dictionaries:

108. Using type() for Dynamic Class Creation

Create classes dynamically:

109. Using os.path.abspath() for Absolute Paths

Convert a relative path to an absolute path:

110. Using math.prod() for Product of Iterable

Compute the product of an iterable (Python 3.8+):

111. Using time.strftime() for Formatting Time

Format time using strftime:

112. Using tempfile for Temporary Files

Create and manage temporary files:

113. Using itertools.islice() for Slicing Iterables

Slice iterables efficiently:

114. Using contextlib.contextmanager() for Context Managers

Define context managers using contextmanager:

115. Using functools.update_wrapper() for Decorators

Ensure metadata is updated in decorators:

116. Using dataclasses.field() for Default Values

Set default values in dataclasses:

117. Using subprocess.run() for Shell Commands

Run shell commands and capture output:

118. Using pickle for Object Serialization

Serialize and deserialize objects:

119. Using typing.Optional for Optional Types

Specify optional types:

120. Using argparse for Command-Line Parsing

Parse command-line arguments with argparse:

121. Using os.environ for Environment Variables

Access environment variables:

122. Using shutil for File Operations

Perform high-level file operations:

123. Using mmap for Memory-Mapped File Access

Access files via memory mapping:

124. Using heapq.nlargest() for Largest Elements

Get the largest n elements:

125. Using collections.OrderedDict for Order Preservation

Preserve the order of dictionary keys (Python 3.6+ dicts are ordered by default):

126. Using str.translate() for String Translation

Translate characters in a string:

127. Using collections.abc for Abstract Base Classes

Check if an object is an instance of an abstract base class:

128. Using math.ceil() for Ceiling Function

Round numbers up to the nearest integer:

129. Using uuid for Unique Identifiers

Generate unique identifiers:

130. Using os.path.splitext() for File Extensions

Split the filename into name and extension:

131. Using inspect.getmembers() for Object Attributes

Retrieve all members of an object:

132. Using collections.UserDict for Custom Dictionaries

Create custom dictionary-like objects:

133. Using os.path.expanduser() for User Paths

Expand ~ to the full user directory path:

134. Using 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

Measure the execution time of code snippets:

137. Using functools.singledispatch() for Generic Functions

Define functions that behave differently based on type:

138. Using subprocess.Popen() for Advanced Process Management

Start and manage subprocesses:

139. Using collections.deque for Efficient Queues

Implement FIFO or LIFO queues:

140. Using getattr() with Dynamic Attributes

Dynamically access attributes:

141. Using contextlib.ExitStack() for Multiple Context Managers

Manage multiple context managers:

142. Using functools.lru_cache() for Memoization

Cache function results:

143. Using logging.basicConfig() for Basic Logging Setup

Configure logging settings:

144. Using collections.defaultdict for Automatic Default Values

Automatically initialize dictionary values:

145. Using os.path.dirname() for Directory Name

Get the directory name from a path:

146. Using itertools.cycle() for Cycling through Iterables

Repeat elements indefinitely:

147. Using collections.Counter for Element Counting

Count element frequencies:

148. Using functools.wraps to Preserve Metadata

Preserve metadata in decorators:

149. Using dataclasses.asdict() for Converting Dataclasses to Dictionaries

Convert dataclasses to dictionaries:

150. Using uuid.uuid1() for Time-Based UUIDs

Generate UUID based on the current time:

Here are 50 more Python tricks to further enhance your skills:

151. Using itertools.starmap() for Argument Unpacking

Apply a function to arguments unpacked from an iterable:

152. Using collections.namedtuple() for Immutable Objects

Create simple classes with named fields:

153. Using __slots__ to Save Memory

Define fixed attributes to save memory:

154. Using bytearray() for Mutable Bytes

Create a mutable byte array:

155. Using pathlib.Path for Path Operations

Work with filesystem paths using an object-oriented approach:

156. Using collections.ChainMap for Multi-Dict Lookup

Combine multiple dictionaries:

157. Using traceback.format_exc() for Exception Tracebacks

Get a formatted traceback of an exception:

158. Using dataclasses.replace() for Copying Instances

Create a new instance with some fields replaced:

159. Using ast.literal_eval() for Safe Evaluation

Safely evaluate strings containing Python literals:

160. Using math.comb() for Combinations (Python 3.8+)

Calculate combinations:

161. Using contextlib.suppress() for Silencing Exceptions

Suppress specified exceptions:

162. Using itertools.product() for Cartesian Products

Compute Cartesian products:

163. Using types.SimpleNamespace for Dynamic Attributes

Create objects with dynamic attributes:

164. Using decimal.Decimal for Precision Arithmetic

Perform precise decimal arithmetic:

165. Using collections.Counter.most_common() for Top Elements

Get the most common elements:

166. Using types.FunctionType for Dynamic Function Creation

Create functions dynamically:

167. Using os.path.join() for Path Construction

Construct file paths:

168. Using functools.total_ordering() for Ordering Methods

Simplify class ordering methods:

169. Using os.path.basename() for Base Filename

Extract the base name of a file:

170. Using collections.defaultdict with Functions

Initialize defaultdict with a function:

171. Using inspect.getargspec() for Function Arguments

Get function argument details:

172. Using random.choices() for Random Sampling with Replacement

Randomly sample elements with replacement:

173. Using heapq.heappush() for Priority Queues

Push elements onto a priority queue:

174. Using warnings.warn() for Warning Messages

Issue warnings:

175. Using os.makedirs() for Creating Directories

Create directories recursively:

176. Using inspect.getmembers() for Inspecting Classes

List all members of a class:

177. Using textwrap.fill() for Wrapping Text

Wrap text to a specific width:

178. Using collections.abc.Callable for Callable Check

Check if an object is callable:

179. Using pickle.HIGHEST_PROTOCOL for Pickle Protocol

Use the highest protocol for pickling:

180. Using socket.gethostname() for Hostname

Get the local machine's hostname:

181. Using contextlib.ExitStack() for Multiple Context Managers

Manage multiple context managers efficiently:

182. Using datetime.timedelta for Date Differences

Compute differences between dates:

183. Using string.Template for String Substitution

Perform string substitutions:

184. Using functools.reduce() for Reducing Iterables

Reduce an iterable to a single value:

185. Using decimal.getcontext() for Decimal Precision

Set and get decimal precision:

186. Using itertools.combinations() for Combinations

Generate

all possible combinations:

187. Using re.sub() with Functions

Replace text using functions:

188. Using os.getenv() for Environment Variables

Get environment variable values:

189. Using itertools.islice() for Slicing Iterables

Slice iterables efficiently:

190. Using binascii.hexlify() for Binary to Hex Conversion

Convert binary data to hexadecimal:

191. Using functools.partial() for Function Specialization

Create a specialized version of a function:

192. Using pickle.load() and pickle.dump() for Serialization

Serialize and deserialize objects:

193. Using threading.Thread for Concurrency

Run code in parallel threads:

194. Using functools.cached_property for Cached Properties

Cache property results:

195. Using uuid.uuid4() for Random UUIDs

Generate a random UUID:

196. Using dataclasses.field() for Field Defaults

Set default values for dataclass fields:

197. Using io.StringIO for In-Memory Text Streams

Create an in-memory text stream:

198. Using ctypes for Calling C Functions

Call C functions from Python:

199. Using operator.attrgetter() for Attribute Access

Access attributes using a getter function:

200. Using unittest.mock.patch() for Mocking

Mock objects for testing:

Last updated