-4
print('code1')
a = [1, 2, 3, 4]
if (len(a)) > 3:
    print(f"List is too long ({len(a)} elements, expected <= 3)")
print('--------------------------------')
print('code2')
a = [1, 2, 3, 4]
if (n := len(a)) > 3:
    print(f"List is too long ({n} elements, expected <= 3)")
print('--------------------------------')
print('code3')
a = [1, 2, 3, 4]
n = len(a)
if n > 3:
    print(f"List is too long ({n} elements, expected <= 3)")

I know code 1 is not an efficient code with respect to codes 2 and 3. But do codes 2 and 3 have the same efficiency ratio together? despite of code 2 is more cleaner thant code 3 just efficentcy?

i 've confusing about this

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Liam
  • 11
  • 3
  • Why do you expect there to be a difference in efficiency at all? (You can compare the bytecode with the `dis` module to answer that question with 100% certainty yourself). – Charles Duffy Aug 14 '23 at 11:07
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 14 '23 at 11:08
  • 1
    (Do note that to be on-topic here, a question needs to be about a specific, practical problem you actually face; do you have an efficiency problem that you believe may be related to walrus operator usage?) – Charles Duffy Aug 14 '23 at 11:08
  • 1
    The complexity of `len()` is `O(1)` so there shouldn't be any performance differences for calling `len()` several times. Take a look at why [Premature Optimization Is the Root of All Evil](https://stackify.com/premature-optimization-evil/) and don't worry (too much) about performance at this stage of the development. – Sembei Norimaki Aug 14 '23 at 11:10
  • Btw: This is a good question, which doesn't deserve the downvotes it got. OP shows 3 pieces of code, and worries about the performance of calling `len()` several times. Instead shows two alternatives which for him are better, and asks people with more experience about which one is the best option. – Sembei Norimaki Aug 14 '23 at 11:18

0 Answers0