Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line If Not None

#1
Python One Line If Not None

To assign the result of a function get_value() to variable x if it is different from None, use the Walrus operator if tmp := get_value(): x = tmp within a single-line if block. The Walrus operator assigns the function’s return value to the variable tmp and returns it at the same time, so that you can check and assign it to variable x subsequently.

Problem: How to assign a value to a variable if it is not equal to None—using only a single line of Python code?

Example: Say, you want to assign the return value of a function get_value(), but only if it doesn’t return None. Otherwise, you want to leave the value as it is. Here’s a code example:

import random def get_value(): if random.random()>0.5: return None return 1 # Naive approach:
x = 42
tmp = get_value()
if tmp != None: x = tmp
print(tmp)

While this works, you need to execute the function get_value() twice which is not optimal. An alternative would be to assign the result of the get_value() function to a temporary variable to avoid repeated function execution:

x = 42
temp = get_value()
if temp != None: x = temp
print(x)

However, this seems clunky and ineffective. Is there a better way?

Let’s have an overview of the one-liners that conditionally assign a value to a given variable:

Exercise: Run the code. Does it always generate the same result?

Method 1: Ternary Operator + Semicolon


The most basic ternary operator x if c else y consists of three operands x, c, and y. It is an expression with a return value. The ternary operator returns x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative y.

You can use the ternary operator to solve this problem in combination with the semicolon to write multiple lines of code as a Python one-liner.

# Method 1
tmp = get_value(); x = tmp if tmp else x

You cannot run the get_value() function twice—to check whether it returns True and to assign the return value to the variable x. Why? Because it’s nondeterministic and may return different values for different executions.

Therefore, the following code would be a blunt mistake:

x = get_value() if get_value() else x

The variable x may still be None—even after the ternary operator has seemingly checked the condition.



Related articles:

Method 2: Walrus + One-Line-If


A beautiful extension of Python 3.8 is the Walrus operator. The Walrus operator := is an assignment operator with return value. Thus, it allows you to check a condition and assign a value at the same time:

# Method 2
if tmp := get_value(): x = tmp

This is a very clean, readable, and Pythonic way. Also, you don’t have the redundant identity assignment in case the if condition is not fulfilled.



Related Article: The Walrus Operator in Python 3.8

Python One-Liners Book


Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!



https://www.sickgaming.net/blog/2020/09/...-not-none/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How To Kill A Thread In Python? xSicKxBot 0 4 6 hours ago
Last Post: xSicKxBot
  [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 11 10-16-2020, 10:30 PM
Last Post: xSicKxBot
  [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 18 10-10-2020, 08:24 PM
Last Post: xSicKxBot
  [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 18 10-09-2020, 06:13 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 29 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 31 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 34 09-29-2020, 09:02 PM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 36 09-28-2020, 02:36 AM
Last Post: xSicKxBot
  [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 31 09-25-2020, 07:51 PM
Last Post: xSicKxBot
  [Tut] Python One Line Dictionary xSicKxBot 0 40 09-21-2020, 05:58 PM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
Mobile - Tactical shojo RPG, Illusion Co...
Last Post: xSicKxBot
Today 11:01 AM
» Replies: 0
» Views: 0
Microsoft - 3 Teams features that help k...
Last Post: xSicKxBot
Today 11:01 AM
» Replies: 0
» Views: 0
News - Review: GONNER2 – Another Way To ...
Last Post: xSicKxBot
Today 11:01 AM
» Replies: 0
» Views: 0
News - Gallery: Lots Of Gorgeous Hyrule ...
Last Post: xSicKxBot
Today 11:01 AM
» Replies: 0
» Views: 0
News - These Metal Gear Solid Air Jordan...
Last Post: xSicKxBot
Today 11:01 AM
» Replies: 0
» Views: 1
[Tut] How To Kill A Thread In Python?
Last Post: xSicKxBot
Today 05:40 AM
» Replies: 0
» Views: 4
(Indie Deal) FREE Ghost Sweeper, ? NBA 2...
Last Post: xSicKxBot
Today 05:40 AM
» Replies: 0
» Views: 4
News - Nintendo Is Permanently Reducing ...
Last Post: xSicKxBot
Today 04:13 AM
» Replies: 0
» Views: 3
News - Blade Runner: Enhanced Edition De...
Last Post: xSicKxBot
Today 04:13 AM
» Replies: 0
» Views: 5
Humble Ultimate Fantasy Game Development...
Last Post: xSicKxBot
Yesterday 10:00 PM
» Replies: 0
» Views: 7

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020