Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform assignment destructuring using the walrus operator in Python

I can do an assignment destructuring as:

a, b = s.split(' ', 1)

for a string s which has more than one word.

How can we do the same in, say an if or elif, with the latest assignment expression introduced in Python 3.8 (is it possible to have multiple targets) ?

I tried:

if some_thing:
    # some code.
elif (a, b := s.split(' ', 1)) and some_func(a) and some_func(b):
    # some code probably using a and b as well.

I get following error:

elif (a, b := s.split(' ', 1)) and some_func(a) and some_func(b):
NameError: name 'a' is not defined

The reason I want this is because I don't want to split my string unnecessarily if my first condition is satisfied.

like image 449
Austin Avatar asked Dec 07 '19 12:12

Austin


People also ask

How do you use the walrus operator in Python?

In Python 3.8, you can combine those two statements and do a single statement using the walrus operator. So inside of print() , you could say walrus , the new object, and use the operator, the assignment expression := , and a space, and then say True .

How does the walrus operator look in Python?

The := is called the walrus operator because it looks kind of like a walrus on its side: the colon looks sort of like eyes and the equal sign looks kind of like tusks.

What is this := in Python?

There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

How does the walrus operator look in Python group of answer choices name expression name expression name := expression name :: expression?

The operator := is called the walrus operator since it characterizes the look of the walrus. See the colon as eyes and the equal sign as its tusks. The walrus operator is used as an assignment expression. It allows you to assign a value to a variable while also returning the value.


1 Answers

See comment on question re assigning to a tuple. I'm by no means an expert though. Posting the below because it works and I think it may be good enough for you? Basically, save the tuple to one variable, which works, and then you can index it

if some_thing:
    # some code.
elif (split := s.split(' ', 1)):
    if some_func(split[0]) and some_func(split[1]):
        # some code probably using a and b as well.
like image 82
Neil Avatar answered Oct 02 '22 05:10

Neil