'String comparison in tuple or list. Python2 vs Python3
We all probably agree that to compare two strings:
var = "MyString"
print(var is "MyString") # This is not the way we would do it (we don't what to compare the ID)
print(var == "MyString") # This is
Anyway I found a situation where someone was comparing strings using is, the piece of code was working for python 3.x but not for python 2.x
Solving the issue was as simple as replacing the is with ==, but then I wanted to track down why it was working for 3.x but not for 2.x. After some testing I narrowed the problem to the difference between using lists or tuples and how the string ID changes. Now I'm simply stuck bc I don't know what is happening.
Let's see the following piece of code:
tup = ("test", )
lst = ["test"]
print(id("test"))
print(id(lst[0]))
print(id(tup[0]))
For Python3.x all the IDs will be the same.
For Python2.x print(id(tup[0])) will print a different ID.
I don't really know who to formulate my question so I will just say, why? What's the difference between py2 and py3? There is something that I'm missing about ID or string IDs that would solve my question?
Thx you all
Edit: I'm running python 2.7.5 on linux
Solution 1:[1]
Can you please provide the exact Python 2.7 version that you're using? Using 2.7.18 gives the same ID for all three examples, so if there was a change it will be been subversions of 2.7 instead of 2.7 -> 3.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Don |
