90 questions
387
votes
6
answers
404k
views
What does colon equal (:=) in Python mean?
What does the := operand mean, more specifically for Python?
Can someone explain how to read this snippet of code?
node := root, cost = 0
frontier := priority queue containing node only
explored := ...
117
votes
7
answers
48k
views
What are assignment expressions (using the "walrus" or ":=" operator)? Why was this syntax added?
Since Python 3.8, code can use the so-called "walrus" operator (:=), documented in PEP 572, for assignment expressions.
This seems like a really substantial new feature, since it allows this ...
32
votes
4
answers
26k
views
Is it possible to add a where clause with list comprehension?
Consider the following list comprehension
[ (x,f(x)) for x in iterable if f(x) ]
This filters the iterable based a condition f and returns the pairs of x,f(x). The problem with this approach is f(x) ...
28
votes
1
answer
2k
views
With assignment expressions in Python 3.8, why do we need to use `as` in `with`?
Now that PEP 572 has been accepted, Python 3.8 is destined to have assignment expressions, so we can use an assignment expression in with, i.e.
with (f := open('file.txt')):
for l in f:
...
24
votes
3
answers
16k
views
Why do I get an infinite while loop when changing initial constant assignment to "walrus operator"?
I'm trying to understand the walrus assignment operator.
Classic while loop breaks when condition is reassigned to False within the loop.
x = True
while x:
print('hello')
x = False
Why doesn'...
24
votes
2
answers
25k
views
Walrus operator in list comprehensions (python)
When coding I really like to use list comprehensions to transform data and I try to avoid for loops. Now I discovered that the walrus operator can be really handy for this, but when I try to use it in ...
22
votes
2
answers
5k
views
How to type hint with walrus operator?
I am trying to type hint a walrus operator expression, i.e.
while (var: int := some_func()): ...
How can I do this?
20
votes
2
answers
6k
views
What is the correct syntax for Walrus operator with ternary operator?
Looking at Python-Dev and StackOverflow, Python's ternary operator equivalent is:
a if condition else b
Looking at PEP-572 and StackOverflow, I understand what Walrus operator is:
:=
Now I'm trying ...
19
votes
2
answers
2k
views
Why do f-strings require parentheses around assignment expressions?
In Python (3.11) why does the use of an assignment expression (the "walrus operator") require wrapping in parentheses when used inside an f-string?
For example:
#!/usr/bin/env python
from ...
17
votes
2
answers
8k
views
Why can't Python's walrus operator be used to set instance attributes?
I just learned that the new walrus operator (:=) can't be used to set instance attributes, it's supposedly invalid syntax (raises a SyntaxError).
Why is this? (And can you provide a link to official ...
15
votes
1
answer
3k
views
Why does "if not a := say_empty()" raise a SyntaxError?
PEP 572 introduces the assignment operator ("walrus operator").
I tried to negate a condition:
def say_empty():
return ''
if not a := say_empty():
print("empty")
else:
...
15
votes
2
answers
5k
views
walrus operator in dict comprehension
I wanted to avoid double evaluation of a mean in a dict comprehension, and I tried using the walrus operator:
>>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C":...
14
votes
1
answer
21k
views
Using a walrus operator in if statement does not work
I have a simple function that should output a prefix based on a pattern or None if it does not match. Trying to do a walrus it does not seem to work. Any idea?
import re
def get_prefix(name):
if ...
13
votes
1
answer
1k
views
Can assignment expressions be enabled in Python 3.7 using __future__?
Python 3.8 introduces assignment expressions, described in PEP 572. Is there a way to test this new feature in Python 3.7.x?
In the past, new language features have been backported to earlier Python ...
11
votes
1
answer
2k
views
Can you combine the addition assignment ( += ) operator with the walrus operator ( := ) in Python?
This is the code I write right now:
a = 1
if (a := a + 1) == 2:
print(a)
I am wondering if something like this exists:
a = 1
if (a +:= 1) == 2:
print(a)
8
votes
1
answer
1k
views
Order of evaluation of assignment expressions (walrus operator)
I have the following expression:
>>> a = 3
>>> b = 2
>>> a == (a := b)
False
Now, a == 2 after the operation, as expected. And the result is what I would want, i.e., ...
8
votes
1
answer
1k
views
How to Avoid Leaking of Python Assignment Expressions in Comprehensions
In the Effective Python book, the author recommends using assignment expressions to avoid redundancy in comprehensions, for example:
def fun(i):
return 2 * i
result = {x: y for x in [0, 1, 2, 3] ...
6
votes
3
answers
3k
views
How to rewrite this simple loop using assignment expressions introduced in Python 3.8 alpha?
It appears to me that it is not that straight forward to interchange classic while loops with assignment-expressions-loops keeping the code looking great.
Consider example1:
>>> a = 0
>&...
6
votes
1
answer
2k
views
Why does using the walrus operator on a member variable raise a SyntaxError?
Why can't I use the walrus operator := to assign to an attribute? It works when assigning to a local variable:
my_eyes = ["left", "right"]
if saved_eye := my_eyes.index("left&...
6
votes
2
answers
3k
views
Two Walrus Operators in one If Statement
Is there a correct way to have two walrus operators in 1 if statement?
if (three:= i%3==0) and (five:= i%5 ==0):
arr.append("FizzBuzz")
elif three:
arr.append("Fizz")
elif ...
5
votes
1
answer
5k
views
Multiple conditions for "walrus operator" assignment
I'd like to know if it's possible to use the "walrus operator" to assign the value based on some condition as well as existing. For example, assign the string to post_url if that string contains some ...
5
votes
2
answers
2k
views
How can named expressions be interpreted in f-strings?
I am trying to use named expressions inside a f-string:
print(f"{(a:=5 + 6) = }")
Returns:
(a:=5 + 6) = 11
But I am hoping for something like this:
a = 11
Is that possible, by combining the walrus ...
5
votes
3
answers
2k
views
How to check if the Enter key was pressed while using the Walrus operator in Python?
I'm trying to get input from a user using the Walrus operator :=, but if the user will only type in the Enter key as input, than the python script will terminate. How can I catch this error and make ...
4
votes
1
answer
4k
views
Python 3.8 Walrus Operator with not and assigning mutliple variables
I am working on a selenium wrapper. I want to check if an element on the webpage is visible . The function gets the input variable selector which follows the pattern "selector=value" so e.g &...
4
votes
1
answer
1k
views
Why isn't the walrus operation a valid statement?
I was doing some python in a terminal, at a point I wrote x := 1 and it showed a Syntax Error.
>>> x := 1
File "<stdin>", line 1
x := 1
^
SyntaxError: invalid ...
4
votes
1
answer
3k
views
Understanding the reason for the new python := operator
This is kind of a meta programming question: I'd like to understand why python developers introduced yet another operator with the new :=. I know what it's for. I would, however, like to know, why the ...
3
votes
1
answer
961
views
Unpack a tuple and assign a variable to the second value only if the first value is truthy
I have a Python function which returns a tuple with a boolean and string
def check_something():
# ...
return bool_value, str_messsage
Is there a way I can use the output of this function in ...
3
votes
5
answers
198
views
Sequence of function iterations
Is there a way to abuse assignment expressions or functional tools to generate the sequence x, f(x), f(f(x)), ... in one line?
Here are some contrived examples to demonstrate:
def iter(x, f, lim=10):
...
3
votes
2
answers
311
views
Equivalent of Python's Walrus operator (:=) in Julia
In python you can write
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
is there an equivalent feature in Julia?
3
votes
2
answers
911
views
Walrus Operator Doesn't Assign Variable?
Playing with the walrus operator, I have this implementation of merge sort:
def mergesort(array):
if len(array) == 1:
output = array
else:
pivot = len(array) // 2
left =...
3
votes
1
answer
1k
views
In Python, What is the order of operations for the walrus operator? [duplicate]
It would be very useful if someone could give the answer by adding a W into PEMDAS. Thanks.
3
votes
3
answers
746
views
Python 3.8 assignment expression in a list comprehension
I'm trying to use the new assignment expression for the first time and could use some help.
Given three lines of log outputs:
sin = """Writing 93 records to /data/newstates-900.03-07_07/top100....
3
votes
1
answer
482
views
How can an assignment statement "x = y := f(x)" be done when using assignment expressions in Python?
I read in Twitter:
#Python news: Guido accepted PEP 572. Python now has assignment expressions.
if (match := (pattern.search) pattern.search(data)) is not None:
print((match.group) mo.group(1)...
3
votes
1
answer
522
views
Pylint is not suggesting the walrus operator. Why?
I was going to ask if there is a pylint-style code analyzer capable of suggesting the use of the := operator in places were it might improve the code. However, it looks like such test has been added ...
3
votes
2
answers
1k
views
Walrus operator in dict declaration
I want to use the walrus operator in a dictionary declaration. However the : is propably causing a problem. I have a dictionary declaration nested in a list comprehension, but I don't want to ...
2
votes
1
answer
98
views
On this Conditional Expression, what the syntax error about?
I get:
return r.group() if r := re.match(rx,l) else None
^
SyntaxError: invalid syntax
whereas
return r.group() if (r := re.match(rx,l)) else None
is accepted.
What ...
2
votes
2
answers
2k
views
Why is the Walrus Operator not working when implemented inside the return statement of this function?
I was trying to solve this problem when I thought of implementing the operator inside the return statement. Here is the question:
Digital root is the recursive sum of all the digits in a number.
Given ...
2
votes
1
answer
1k
views
Walrus operator in Python interpreter
When I use the walrus operator as below in the Python(3.9.6)
interpreter,
>>> walrus:=True
I get a syntax error:
File "<stdin>", line 1
walrus := True
...
2
votes
1
answer
404
views
How to Use the Walrus Operator (:=) in a Lambda Function within pandas.DataFrame.apply
I have the following minimal working example (specific to python >= 3.8), which converts a file name string into a full path:
# running this block will produce the expected output
import pandas as ...
2
votes
3
answers
267
views
Underscore variable with walrus operator in Python
In Python, the variable name _ (underscore) is often used for throwaway variables (variables that will never be used, hence do not need a proper name).
With the walrus operator, :=, I see the need for ...
2
votes
3
answers
292
views
Can assignment expression create Fibonacci series using list comprehension?
With assignment expression, I thought I could try list comprehension to create Fibonacci. I first initialize a Fibonacci list of 5 elements f = [1,2,3,4,5] with the first two values being the seeds.
...
2
votes
1
answer
216
views
Python: Is there a Walrus Operator for slices of an object?
My question is, in all of the walrus examples, they use the whole object for the boolean, e.g.
if (x := len(s)) > 5:
print(x)
converts
x = len(s)
if x > 5:
print(x)
Is there a way to ...
2
votes
1
answer
447
views
operator or method in swift which work as walrus operator of python
walrus operator of python language ( := )
work:- assign the value & also return that value.
language like swift at value assign it return nothing.
how to implement walrus operator kind a thing ...
1
vote
3
answers
61
views
Warlus Operator conversion
I have a piece of code involving walrus operator. I am trying to convert it to normal python code. But I am not sure if it is happening correctly or not.
# code with warlus
NUM_ELEMS = cpu_count()
...
1
vote
3
answers
153
views
Odd Syntax (Walrus operator in inheritance)
I was looking in python's grammar and was that you could use the walrus operator in inheritance! Not believing it, I tried it out:
class foo: pass
class bar(foobar := foo):
def x(self):
...
1
vote
2
answers
153
views
Can a walrus expression be put inside square brackets rather than parentheses?
Take the following code:
k = 'A'
d = {}
d[k := k.lower()] = 'b'
print(k)
print(d)
This gives the output one would expect:
a
{'a': 'b'}
However, for similar code in a project of mine, flake8 ...
1
vote
2
answers
981
views
Walrus operator assign variable if method does return None
I read the documentation and lots of examples but do not fully understand how to use it.
I have a function, screen() that returns a screenshot but may return None. I call this in a loop to a variable. ...
1
vote
2
answers
61
views
Build dict from list of pairs that is made from string
Say we have a string like
s = "a=b&c=d&xyz=abc"
I would like to get dictionary
{"a": "b", "c": "d", "xyz": "abc"}
This ...