90 questions
-5
votes
1
answer
127
views
How do I fix this error with the walrus operator? [closed]
I'm doing a simple task and my "solution" raised an error. I am using the walrus operator (:=) improperly but I would like to know how I can change my code to use it properly.
Code basically ...
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):
...
-4
votes
1
answer
124
views
For-loop with the walrus operator inside the range
Why are the negative k values being printed as the original value, but when we enter the positive realm, it gets strange?
In:
def j(k):
for i in range(i:=k):
i+=i
print(i)
for i in [-5,...
-3
votes
1
answer
148
views
Python walrus operator. Can I use two != != in walrus operator?
I'm new to programming. I'm learning the walrus operator. I want the while loop end/stop when someone type quit or finish. Only quit works. when someone type "finish", it produces an output ...
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 ...
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
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 ...
0
votes
1
answer
72
views
Can any usage of the assignment operator technically be replaced with the walrus operator surrounded by parentheses?
Say we have this assignment statement:
a = 5
Even though it'd obviously be ugly to do this for no reason, we could technically accomplish the same thing with:
(a := 5)
This still assigns 5 to a, and ...
-1
votes
1
answer
135
views
Can these sorts of if/else statements be boiled down with a walrus operator?
I have read up blogs and tutorials around the := operator but I am still trying to wrap my head around how to know when to use it. I understand its purpose is to improvement maintainability, avoiding ...
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 ...
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 ...
0
votes
1
answer
102
views
Find fibonacci series upto N terms using list comprehension
Need to find the Fibonacci series up to N terms.
n=int(input("Enter the n terms: "))
f_val=0
fib_list=[f_val:=f_val + i for i in range(n)]
print(fib_list)
While executing the above program, ...
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?
-1
votes
1
answer
138
views
Why are those algorithm so different in term of their execution time ? Is the walrus operator less time consuming in Python?
While making a function to manipulate the TypeVar from the typing module, I came across a problem.
My function do work but I wanted to make it faster so I used the timeit module to test some different ...
-3
votes
1
answer
2k
views
What is the difference between := and ::= in Python?
I see Python examples with := and ::=. I've got a good understanding of the walrus operator from an article on RealPython(The Walrus Operator: Python 3.8 Assignment Expressions). I also went through ...
0
votes
3
answers
90
views
Expression that returns mutated list
I'm looking for a single expression, mutates an element and returns the modified list
The following is a bit verbose
# key=0; value=3; rng=[1,2]
[(v if i != key else value) for i, v in enumerate(rng)]
...
1
vote
1
answer
156
views
Attemtping to solve twoSums leet code problem why doesn't the walrus operator with dict.get() work in python3
Prompt: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and ...
0
votes
2
answers
504
views
Walrus to unpack values within a list comprehension
I have a nested list holding dictionaries as mapping table using a tuple as key. I am struggling to zip the dictionary together so it can be exported by Pandas to csv file:
l = [{('A', 'B'): 1}, {('A',...
0
votes
1
answer
2k
views
Why is it that I "cannot use assignment expressions with comparison" in Python?
In the examples below, x is assigned using the walrus operator and is then printed.
mystring = "hello, world"
#if 1
if x := mystring == "hello, world":
print(x)
#if 2
if x := (...
0
votes
2
answers
356
views
Why is the walrus operator not a delimiter?
The Python walrus operator (:=) is listed in the documentation as an operator, but not as a delimiter like the rest of the assignment operators (e.g. +=). Why then is the walrus operation not also a ...
0
votes
0
answers
6k
views
Why is Python walrus operator (:=) needed instead of just using the normal assignment operator (equal sign)? [duplicate]
I just learned there is a walrus operator in Python 3.8
if a := 2 + 3:
print(a) # 5
I wonder why they created a new operator instead of allowing the existing assignment operator as expression, ...
0
votes
4
answers
971
views
why can't I use walrus in a one-line for expression
I'm trying to use walrus in a for loop to create a list,
something like this:
data = [l := line.strip().somefunc() for line in iterable_obj if(l[0] == 'sth')]
but it returns an empty list
can someone ...
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 ...
0
votes
2
answers
60
views
Use Output from expression part of list comprehension in conditional [duplicate]
I want to call a method and add the returned value to a list only if the value is not None, in place.
Approach 1
list = []
for item in items:
temp = func(item)
if temp is not None:
...
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 ...
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
0
answers
78
views
Pythonic way to assign variable before entering for loop
I am iterating over a list of strings and matching whether the target version of last string matches current version of present string.
My solution to this problem is:
regex_pattern = r"^(\w+)-to-...
-1
votes
1
answer
580
views
Can't get the walrus operator to work (Python double list comprehension)
This list comprehension does not work:
buy_prices = [(buylow := round(0.997 + ii/10000.0, 5), max(jj, buylow)) for jj in [buylow, 0.9982] for ii in range(21)]
NameError: name 'buylow' is not defined
...
-3
votes
3
answers
2k
views
Using a while loop walrus operator with a generator
I'd like to use a walrus operator with a simple generator in a while loop
def gen():
for i in range(5):
yield i
yield 10
g = gen()
while i := next(g):
print(i)
I expect the ...
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 ...
-1
votes
2
answers
327
views
python: walrus operator and re.search() in list comprehension
I have a list of strings and I want to extract a pattern from elements.
For instance, given list ["A 12345bcd", "BYT 676 CCC"] and pattern r'\d\d\d\d\d', I would like to obtain: [&...
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 ...
1
vote
3
answers
131
views
Can this loop be done in a list comprehension?
Comming from this question
Adding the last position of an array to the same array
I was curious if the mentioned loop can be done in a list comprehension?
array = [3,4,2,5,4,5,8,7,8,9]
value = 10
for ...
1
vote
1
answer
59
views
How to properly use assignment operator with mod operator in an if statement?
I am trying to use the Walrus operator in python with different if statements and the code that i am trying to replace looks like this:
from time import time
n = 10
numbers = []
results = []
def ...
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 =...
-1
votes
2
answers
102
views
Why does using an assignment expression in a loop condition store a bool value?
This code stores your favorite foods in a list, but the input turns into a bool type character. Why is this happening and how can I fix it?
foods=list()
while food := input("what food do you like?...
0
votes
1
answer
352
views
yield with walrus operator := causes syntax error
import contextlib
from win32com.client import Dispatch
@contextlib.contextmanager
def excel_ctx() -> Generator[Dispatch, None, None] :
try:
yield excel := Dispatch("Excel....
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 ...
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":...
0
votes
2
answers
694
views
Python3.8 assignment expressions, use in list comprehension or as an expression
I recently discovered that assignment expressions exist. And I wanted to refactor some of my code to make use of them. Most of the places I wanted to use it were relatively straightforward to ...
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 &...
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
...
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., ...
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 ...
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.
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)
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 ...
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 ...