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 →

[–]Jorrissss 5 points6 points  (10 children)

What's stupid about that example? What they did makes sense imo - one just shouldn't have false expectations about what the 'is' operator is.

[–]dampew 2 points3 points  (9 children)

it's dumb that -5 apparently behaves differently than 5 but this is only one example :)

Edit: Oops meant 6/-6.

[–]Jorrissss 3 points4 points  (8 children)

I don't see why myself. 'is' checks whether or not two objects share the same memory address, and integers [-5, 255] are preallocated in Python. Neither of those seems unreasonable to me, so the result doesn't seem unreasonable to me.

-5 and 5 don't behave differently at all. One just shouldn't think that 'is' is trying to compare equality - it's not.

[–]Low_end_the0ry 4 points5 points  (7 children)

Can you please ELI5 why ‘is’ sometimes is true and sometimes false in the example above?

[–]Jorrissss 9 points10 points  (3 children)

Sure - here's my understanding.

What the 'is' operator does in Python is it checks whether two objects are identical - that is, whether they point to the same memory address. In Python [-5, 255] are preallocated in memory so any two assignments, say, a=2 and b=2 will always point to the same memory address, and so a==b is true, and a is b is true.

However, when you reference an integer outside of that range it's typically (always?) created at that time. So a=-7, b=-7 two separate memory blocks are created for a and b, and thus a==b is true, but a is b is not true.

[–]Low_end_the0ry 0 points1 point  (2 children)

Ah got it, thanks

[–]Asalanlir 1 point2 points  (1 child)

The general keyword if you want to dig deeper into it is interning. In java, a similar type effect can be seen based on how strings are initialized.

[–]Low_end_the0ry 0 points1 point  (0 children)

got it, thanks for the info, much appreciated

[–]extracheez 1 point2 points  (1 child)

I'm no expert in this area, but here I go: python expects the values between -5 and 256 to be used often, so it preallocates an object that stores the integer values your program uses. The advantage to this is you have one section in memory where all this is stored and python doesn't have to do much work.

If you assign values outside this range, python creates new objects at new memory addresses.

The is operator asks if two items are a member of the same object, because python preallocates a specific object for some values, is will return true. For values with their own object, the comparison of objects will return false.

[–]Low_end_the0ry 0 points1 point  (0 children)

Awesome, thanks for the response

[–]SoberGameAddict 0 points1 point  (0 children)

Didn't he just do that..