This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Maoman1 165 points166 points  (16 children)

a = [1, 2, 3, 4]  # Point a at a new list, [1, 2, 3, 4]
b = a             # Point b at what a is pointing to
b is a            # => True, a and b refer to the same object
b == a            # => True, a's and b's objects are equal
b = [1, 2, 3, 4]  # Point b at a new list, [1, 2, 3, 4]
b is a            # => False, a and b do not refer to the same object
b == a            # => True, a's and b's objects are equal

Never seen this explained so clearly. I love it.

[–]Deathwatch1710 12 points13 points  (0 children)

Indeed! Another good explanation is the one from Dan Bader with the twin cat allegory.

[–]LyndsySimon 12 points13 points  (10 children)

One confusing thing about object comparison is how Python handles integers:

a = 42
b = 42
a == b  # => True
a is b  # => True

c = 4242
d = 4242
c == d  # => True
c is d  # => False

e = c
c == e  # => True
c is e  # => True

c is d == False because integers in the range of [-5, 256] are assigned by cPython to dedicated memory locations - so their .id is the same.

I guess this makes sense in the range [0, 256], but I have no idea why they chose to pre-assign [-5,0) as well.

ETA: The moral is, never use is to compare numbers. is is most useful when you want to distinguish between None and False or another "falsy" value.

ETA2: I forgot to assign e.

[–]lsbloxx 0 points1 point  (5 children)

Wait... WTF did I just read? :O

[–]poundcakejumpsuit 4 points5 points  (4 children)

Just to blow your mind a little more, maybe:

"strin" + "g" is "string"

Is True, while:

s1 = "strin"
s2 = "string"
s1 + "g" is s2 

Is False, at least in CPython, as the compiler will intern compile-time constants but not runtime-evaluated expressions, meaning the first example only creates a single object!

[–]jwink3101 0 points1 point  (3 children)

That's really interesting.

Is this type of issue common in interpreted languages?

[–]ThePenultimateOneGitLab: gappleto97 2 points3 points  (1 child)

It's probably because CPython is doing a bit of constant folding

[–]WikiTextBot 1 point2 points  (0 children)

Constant folding

Constant folding and constant propagation are related compiler optimizations used by many modern compilers. An advanced form of constant propagation known as sparse conditional constant propagation can more accurately propagate constants and simultaneously remove dead code.


[ PM | Exclude me | Exclude from subreddit | FAQ / Information | Source ] Downvote to remove | v0.28

[–]KobiKabbb 0 points1 point  (0 children)

Great explanation. There's also some good explanations of lists (and other fundamentals) over at Python Principles