20 extremely useful single-line Python codes
<blockquote>
<p>Hello everyone, in this article, I am sharing with you 20 Python one-liner codes that you can easily learn in 30 seconds or less. These one-liner codes will save you time and make your code look cleaner and more readable.</p>
</blockquote>
<p><strong>1.One-line For Loop</strong></p>
<p>For loops are multi-line statements, but in Python, we can write for loops in one line using list comprehension methods. As an example, to filter out values less than 250, take a look at the following code example.</p>
<pre>
#For loop in one line
mylist = [200, 300, 400, 500]
#Single line For loop
result = []
for x in mylist:
if x > 250:
result.append(x)
print(result) # [300, 400, 500]
#One-line code way
result = [x for x in mylist if x > 250]
print(result) # [300, 400, 500]</pre>
<p><strong>2 .One-Line While Loop</strong></p>
<p>This One-Liner segment will show you how to use While loop code in one line, with two different methods demonstrated.</p>
<pre>
#Method 1 Single Statement
while True: print(1) #infinite 1
#Method 2 Multiple Statements
x = 0
while x < 5: print(x); x= x + 1 # 0 1 2 3 4 5</pre>
<p><strong>3 .One-Line IF Else Statement</strong></p>
<p>Alright, to write an IF Else statement in one line we will use the ternary operator. The syntax for the ternary is “[on true] if [expression] else [on false]”.</p>
<p>I have shown 3 examples in the sample code below to make it clear to you on how to use the ternary operator for a one-line if-else statement. To use an Elif statement, we must use multiple ternary operators.</p>
<pre>
#if Else In a single line.
#Example 1 if else
print("Yes") if 8 > 9 else print("No") # No
#Example 2 if elif else
E = 2
print("High") if E == 5 else print("数据STUDIO") if E == 2 else
print("Low") # Data STUDIO
#Example 3 only if
if 3 > 2: print("Exactly") # Exactly</pre>
<p><strong>4.</strong><strong>Merging dictionaries in one line</strong></p>
<p>This one-liner code segment will show you how to merge two dictionaries into one using a single line of code. Here, I’ve presented two methods for merging dictionaries.</p>
<p><a href="https://medium.com/@hafizabdullaha93/20-extremely-useful-single-line-python-codes-de44928a1a3b">Visit Now</a></p>