473,385 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

Hi,
(len(['']) is 1) == (len(['']) == 1) =True

Is this the case for all numbers? I've tried running the following:

for i in range(10000):
for j in range(10000):
if i != j:
assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id
(i))

which executes fine. Hence, 0-9999 is okey... But this is a relatively
small range, and sooner or later you probably get two numbers with the same
id... Thoughts anyone?

Regards Tor Erik

PS: For those of you who don't know: keyword is compares object identities
Nov 23 '06 #1
14 1275
Tor Erik Soenvisen wrote:
(len(['']) is 1) == (len(['']) == 1) =True

Is this the case for all numbers?
I'm not sure what you're asking here, but if you digest the following
facts, maybe you can answer it yourself:

1) all objects that exist at the same time have distinct identifies, and
2) a Python implementation may or may not hand reuse existing immutable
objects that have the same value when asked to create a new object,
3) identities are recycled when objects are deleted, and
4) [] and {} always create a new object every time they're evaluated.

</F>

Nov 23 '06 #2
Tor Erik Soenvisen wrote:
(len(['']) is 1) == (len(['']) == 1) =True

Is this the case for all numbers? I've tried running the following:

for i in range(10000):
************for*j*in*range(10000):
****************if i != j:
************************assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i,
(i))
Shouldn't the test in the loop be

if i == j:
assert i is j
Of course it would fail...

Peter
Nov 23 '06 #3
distinct identifies

don't trust your spellchucker.

</F>

Nov 23 '06 #4

"Tor Erik Soenvisen" <to******@hotmail.comwrote in message
news:Xn*****************************@129.242.5.222 ...
which executes fine. Hence, 0-9999 is okey... But this is a relatively
small range, and sooner or later you probably get two numbers with the same
id... Thoughts anyone?
I think you are confusing yourself unnecessarily. The obvious way to implement
unique ids is to return the address of the object. It's very unlikely that two
different objects share the same address.
Nov 23 '06 #5
On Thu, 23 Nov 2006 10:48:32 +0000, Tor Erik Soenvisen wrote:
Hi,
(len(['']) is 1) == (len(['']) == 1) =True
You shouldn't rely on this behaviour:
>>x = 100000
len('a' * x) == x
True
>>len('a' * x) is x
False

(Your results may vary -- this depends on the implementation.)
Is this the case for all numbers? I've tried running the following:

for i in range(10000):
for j in range(10000):
if i != j:
assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id
(i))

which executes fine. Hence, 0-9999 is okey...
This doesn't necessarily hold for all integers -- again, it depends on the
implementation, the precise version of Python, and other factors. Don't
rely on "is" giving the same results as "==".
>>(1+2+3+4+5)**7 == 15**7
True
>>(1+2+3+4+5)**7 is 15**7
False
But this is a relatively
small range, and sooner or later you probably get two numbers with the same
id... Thoughts anyone?
No, you will never get two objects existing at the same time with the same
id. You will get two objects that exist at different times with the same
id, since ids may be reused when the object is deleted.
PS: For those of you who don't know: keyword is compares object identities
Exactly. There is no guarantee that any specific integer object "1" must
be the same object as another integer object "1". It may be, but it isn't
guaranteed.

I think the only object that is guaranteed to hold for is None. None is a
singleton, so there is only ever one instance. Hence, you should test for
None with "obj is None" rather than ==, because some custom classes may do
silly things with __eq__:

class Blank(object):
"""Compares equal to anything false, including None."""
def __eq__(self, other):
return not other

--
Steven.

Nov 23 '06 #6
Steven D'Aprano <st***@REMOVE.THIS.cybersource.com.auwrote in
news:pa****************************@REMOVE.THIS.cy bersource.com.au:
On Thu, 23 Nov 2006 10:48:32 +0000, Tor Erik Soenvisen wrote:
>Hi,
(len(['']) is 1) == (len(['']) == 1) =True

You shouldn't rely on this behaviour:
>>>x = 100000
len('a' * x) == x
True
>>>len('a' * x) is x
False

(Your results may vary -- this depends on the implementation.)
>Is this the case for all numbers? I've tried running the following:

for i in range(10000):
for j in range(10000):
if i != j:
assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id
(i))

which executes fine. Hence, 0-9999 is okey...

This doesn't necessarily hold for all integers -- again, it depends on
the implementation, the precise version of Python, and other factors.
Don't rely on "is" giving the same results as "==".
>>>(1+2+3+4+5)**7 == 15**7
True
>>>(1+2+3+4+5)**7 is 15**7
False
>But this is a relatively
small range, and sooner or later you probably get two numbers with
the same id... Thoughts anyone?

No, you will never get two objects existing at the same time with the
same id. You will get two objects that exist at different times with
the same id, since ids may be reused when the object is deleted.
>PS: For those of you who don't know: keyword is compares object
identities

Exactly. There is no guarantee that any specific integer object "1"
must be the same object as another integer object "1". It may be, but
it isn't guaranteed.

I think the only object that is guaranteed to hold for is None. None
is a singleton, so there is only ever one instance. Hence, you should
test for None with "obj is None" rather than ==, because some custom
classes may do silly things with __eq__:

class Blank(object):
"""Compares equal to anything false, including None."""
def __eq__(self, other):
return not other

I've seen code like this:

if type([]) is list:
print 'Is list'

which seem to work. And also I've seen "var is None", as you mention.
Nov 23 '06 #7
Steven D'Aprano wrote:
No, you will never get two objects existing at the same time with the
same id. You will get two objects that exist at different times with
the same id, since ids may be reused when the object is deleted.
I think it is worth pointing out that this is an area where people get
confused quite often; it is very easily to get misleading results when you
call the id() function. e.g.
>>class C:
def f(self): pass
def g(self): pass

>>c = C()
id(c.f)==id(c.g)
True
>>c.f is c.g
False

The ids are the same here only because the objects do not exist at the same
time. In the first comparison c.f is an expression which creates a
temporary object that is destroyed before the expression involving c.g is
evaluated, so it is possible for the different objects to have the same id.
In the second comparison the objects exist at the same time so they are
forced to have different ids.
Nov 23 '06 #8
Tor Erik Soenvisen <to******@hotmail.comwrote:
I've seen code like this:

if type([]) is list:
print 'Is list'

which seem to work.
'seem to work' is correct. Occasionally 'type(x) is list' is exactly what
is needed, but much more likely it is a potential bug.

It is more likely that what was intended was: isinstance(x, list)

It is even more likely that the intention was that the object should have
some list-like behaviour, in which case not doing a test at all is the
correct behaviour; or quite often that the object should be list-like but
not a string in which case testing the type against basestring would be
correct. e.g.:

if isinstance(x, basestring):
x = [x]
# ... now just assume x is a suitable sequence ...
for element in x:
...
Nov 23 '06 #9
Tor Erik Soenvisen wrote:
I've seen code like this:

if type([]) is list:
print 'Is list'

which seem to work. And also I've seen "var is None", as you mention.
None is guaranteed to be a singleton:

http://effbot.org/pyref/type-none.htm

Why "is" works for type objects should be pretty obvious, of course.

</F>

Nov 23 '06 #10
Tor Erik Soenvisen wrote:
(len(['']) is 1) == (len(['']) == 1) =True
>>len([''])
1
>>len(['']) is 1
True
>>len(['']) == 1
True
>>True == True
True
>>(len(['']) is 1) == (len(['']) == 1)
True
What did you expect?

Stefan
Nov 23 '06 #11
Fredrik Lundh wrote:
4) [] and {} always create a new object every time they're evaluated.
Not quite. The empty tuple is cached:
>>a = ()
b = ()
a is b
True

Cheers,
Brian
Nov 23 '06 #12
Brian Quinlan wrote:
>4) [] and {} always create a new object every time they're evaluated.

Not quite. The empty tuple is cached:
>>a = ()
>>b = ()
>>a is b
True
() isn't [] or {}, though. time to switch to a bigger font? ;-)

</F>

Nov 23 '06 #13
Fredrik Lundh wrote:
Brian Quinlan wrote:
>>4) [] and {} always create a new object every time they're evaluated.
Not quite. The empty tuple is cached:
> >>a = ()
b = ()
a is b
True

() isn't [] or {}, though. time to switch to a bigger font? ;-)
Yeah, sorry I'm an idiot. I can't believe that I've been able to program
successfully for so long when I can't recognize the different between a
dictionary and a tuple :-)

Cheers,
Brian
Nov 23 '06 #14
Tor Erik Soenvisen <to******@hotmail.comwrote:
>
(len(['']) is 1) == (len(['']) == 1) =True

Is this the case for all numbers? I've tried running the following:

for i in range(10000):
for j in range(10000):
if i != j:
assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id
(i))

which executes fine. Hence, 0-9999 is okey... But this is a relatively
small range, and sooner or later you probably get two numbers with the same
id... Thoughts anyone?
It has been my experience that virtually every use of the "is" operator
(except "is None") is wrong.

Now, I fully understand that there are perfectly valid uses for "is", and
the standard library contains a few, but for the non-guru casual Python
programmer, I think it is safe to say "never use 'is'".
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Nov 23 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Jani Yusef | last post by:
I have a HW problem stated as shown at the top of the solution. The thing is is that I am not 100% sure wtf constant memory means. Well, I think I do but I am confused. Does my solution use contant...
3
by: Fredrik Normann | last post by:
Hello, I'm trying to read the binary files under /var/spool/rwho/ so I'm wondering if anyone has done that before or could give me some clues on how to read those files. I've tried to use the...
22
by: Ben Finney | last post by:
Howdy all, I've recently packaged 'enum' in PyPI. In its description, I make the claim that it creates "immutable" enumeration objects, and that the enumeration values are "constant" values. ...
12
by: Frederick Gotham | last post by:
Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant representing the amount of value representation bits in an unsigned integer type. In true C fashion, here it is as a macro:...
5
by: Orange | last post by:
hi, How to initialize the data variable. typedef struct { long len; BYTE data; }tag;
16
by: Chris | last post by:
Looking at some code I see a declaration inside a function like static const string s("some string"); Does the static serve any purpose here?
5
by: Bruno Ferreira | last post by:
Hi, I wrote a very simple python program to generate a sorted list of lines from a squid access log file. Here is a simplified version: ################################## 1 logfile = open...
7
by: r_ahimsa_m | last post by:
Hello, I am learning JavaScript. I have a table on HTML page:                 <table id="announcement_fields" border="0">                 <tbody>                 <tr>...
5
by: process | last post by:
Python uses arrays for lists right? def quicksort(lista): if lista == : lista else: return quicksort( if x < lista]) + ] + \ quicksort( if x >= lista])
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.