Skip to main content
Filter by
Sorted by
Tagged with
387 votes
6 answers
404k views

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 := ...
Julio's user avatar
  • 3,931
117 votes
7 answers
48k views

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 ...
Chris_Rands's user avatar
  • 41.7k
32 votes
4 answers
26k views

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) ...
balki's user avatar
  • 27.9k
28 votes
1 answer
2k views

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: ...
Antti Haapala's user avatar
24 votes
3 answers
16k views

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'...
Кафка's user avatar
24 votes
2 answers
25k views

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 ...
Jeroen Vermunt's user avatar
22 votes
2 answers
5k views

I am trying to type hint a walrus operator expression, i.e. while (var: int := some_func()): ... How can I do this?
rkoni's user avatar
  • 321
20 votes
2 answers
6k views

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 ...
BhaveshDiwan's user avatar
  • 1,091
19 votes
2 answers
2k views

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 ...
Anil's user avatar
  • 1,459
17 votes
2 answers
8k views

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 ...
Intrastellar Explorer's user avatar
15 votes
1 answer
3k views

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: ...
WoJ's user avatar
  • 30.6k
15 votes
2 answers
5k views

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":...
FAL's user avatar
  • 173
14 votes
1 answer
21k views

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 ...
Bruno Vermeulen's user avatar
13 votes
1 answer
1k views

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 ...
Daniel Mahler's user avatar
11 votes
1 answer
2k views

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)
Nathan Dai's user avatar
8 votes
1 answer
1k views

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., ...
Mad Physicist's user avatar
8 votes
1 answer
1k views

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] ...
Kilian Obermeier's user avatar
6 votes
3 answers
3k views

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 >&...
alec_djinn's user avatar
  • 10.9k
6 votes
1 answer
2k views

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&...
Inyoung Kim 김인영's user avatar
6 votes
2 answers
3k views

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 ...
Joseph Kready's user avatar
5 votes
1 answer
5k views

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 ...
Shaun Barney's user avatar
5 votes
2 answers
2k views

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 ...
Gustav Rasmussen's user avatar
5 votes
3 answers
2k views

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 ...
MendelG's user avatar
  • 20.6k
4 votes
1 answer
4k views

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 &...
Jocomol's user avatar
  • 332
4 votes
1 answer
1k views

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 ...
Was's user avatar
  • 536
4 votes
1 answer
3k views

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 ...
user avatar
3 votes
1 answer
961 views

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 ...
Midhun Mathew Sunny's user avatar
3 votes
5 answers
198 views

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): ...
qwr's user avatar
  • 11.6k
3 votes
2 answers
311 views

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?
Felix Benning's user avatar
3 votes
2 answers
911 views

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 =...
Connor's user avatar
  • 4,984
3 votes
1 answer
1k views

It would be very useful if someone could give the answer by adding a W into PEMDAS. Thanks.
Nathan Dai's user avatar
3 votes
3 answers
746 views

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....
WestCoastProjects's user avatar
3 votes
1 answer
482 views

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)...
fedorqui's user avatar
  • 293k
3 votes
1 answer
522 views

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 ...
VPfB's user avatar
  • 18.1k
3 votes
2 answers
1k views

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 ...
the Radek's user avatar
  • 320
2 votes
1 answer
98 views

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 ...
ChrisJJ's user avatar
  • 2,312
2 votes
2 answers
2k views

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 ...
Hrishi's user avatar
  • 51
2 votes
1 answer
1k views

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 ...
BlueGene's user avatar
  • 1,137
2 votes
1 answer
404 views

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 ...
Trenton McKinney's user avatar
2 votes
3 answers
267 views

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 ...
DustByte's user avatar
  • 863
2 votes
3 answers
292 views

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. ...
Leon Chang's user avatar
2 votes
1 answer
216 views

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 ...
stackz's user avatar
  • 84
2 votes
1 answer
447 views

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 ...
b m gevariya's user avatar
1 vote
3 answers
61 views

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() ...
Ahmad Anis's user avatar
  • 2,742
1 vote
3 answers
153 views

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): ...
xilpex's user avatar
  • 3,305
1 vote
2 answers
153 views

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 ...
Inertial Ignorance's user avatar
1 vote
2 answers
981 views

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. ...
AskedSuperior's user avatar
1 vote
2 answers
61 views

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 ...
Roman Pavelka's user avatar