Reputation: 21
Referred following question -
1) different run results between python3 and python2 for the same code
2) “is” operator behaves unexpectedly with integers
3) Consecutive 'is' operator in Python [duplicate]
5) What does 'is' operator do in Python?
6) Strange python 'is' operator in arithmetic [duplicate]
7) Why does the “is” keyword have a different behavior when there is a dot in the string?
Explanation for not duplicate question - In my question, I have not included any symbol, numeric values. I am including simple string. In above 7th referred question, I already know the reason behind giving different output and I have already read that.
Here, my question is different.
My Question Description -
I am practicing following Python code in 3.6.8 version and using PyCharm editor.
print('a' * 18 is 'aaaaaaaaaaaaaaaaaa')
print('a' * 19 is 'aaaaaaaaaaaaaaaaaaa')
print('a' * 20 is 'aaaaaaaaaaaaaaaaaaaa')
print('a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa')
print('a' * 22 is 'aaaaaaaaaaaaaaaaaaaaaa')
Output =
True
True
True
False
False
Why does 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
and onwards strings not evaluate to True?
Any help would be appreciated
Upvotes: 0
Views: 118
Reputation: 21
Why does 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
and onwards strings not evaluate to True?
From following diagram, The penultimate source code compilation step produces a first version of bytecode. This “raw” bytecode finally goes into a last compilation step called “peephole optimization”. The goal of this step is to produce more efficient bytecode by replacing some instructions by faster ones.
The .pyc files encounter in all Python packages. Python bytecode is stored in these files. What would happen if someone wrote something like this ['foo!'] * 10**9? The resulting .pyc file would be huge! In order to avoid this phenomena, sequences generated through peephole optimization are discarded if their length is superior to 20.
So, in above question, following given code produces False result for the value of length superior to 20 and not produces False for value 20 or less than 20 for string.
print('a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa')
print('a' * 22 is 'aaaaaaaaaaaaaaaaaaaaaa')
output =
False
False
Upvotes: 2