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.
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With