Python Forum
Is the Walrus Operator( := ) antipattern?
Poll: Walrus operator is antipattern and unnecessary
You do not have permission to vote in this poll.
Yes
0%
0 0%
No
100.00%
3 100.00%
Total 3 vote(s) 100%
* You voted for this item. [Show Results]

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is the Walrus Operator( := ) antipattern?
#1
The walrus operator( := ) was introduced in Python 3.8.
It allows you to create, assign and use a variable in the same statement.
Example:
numbers = [1, 2, 3, 4, 5]

squares = [y for x in numbers if (y := x**2) > 10]

print(squares)  
Output:
[16, 25]
I have seen discussion where people argue that this feature is antipattern and makes code unnecessarily obscure. What do you think?
Reply
#2
Perhaps I'm missing something (still being relatively new to Python) but isn't this simpler?

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers if x**2 > 10]
print(squares) 
Not sure what incorporating yet another variable "y" and then using the walrus operator achieves? Undecided
Reply
#3
(Mar-01-2025, 01:22 AM)ArchieLinux Wrote: Perhaps I'm missing something (still being relatively new to Python) but isn't this simpler?
Simpler to understand, but for each element the square is calculated twice if the condition fits.
The combination of a list comprehension and the use of the Walrus operator can be very confusing.
ArchieLinux likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
(Mar-01-2025, 08:27 PM)DeaD_EyE Wrote: Simpler to understand, but for each element the square is calculated twice if the condition fits.
The combination of a list comprehension and the use of the Walrus operator can be very confusing.

Ah, I think I get it... So it's an internal efficiency thing within Python that otherwise wouldn't be obvious from outside. With a larger scale operation I imagine this could then make a performance difference. Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Walrus Operator in 3.8 nilamo 21 13,024 Sep-20-2019, 12:12 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020