473,410 Members | 1,852 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,410 software developers and data experts.

list.__len__() or len(list)

which one is better? and why?

__len__() is a built-in function of the list object and is updated along
with the list object elements and will be useful incase the list is very
huge.

len() is an external method again, which may require the processing
cycles again.

Is it right?
Jun 27 '08 #1
10 6531
On May 13, 6:57*pm, Nikhil <mnik...@gmail.comwrote:
which one is better? and why?

__len__() is a built-in function of the list object and is updated along
with the list object elements and will be useful incase the list is very
huge.

len() is an external method again, which may require the processing
cycles again.

Is it right?
len() is the correct way to do it, methods that begin with __ are
meant to be more internal.
Jun 27 '08 #2
On Tue, May 13, 2008 at 5:57 PM, Nikhil <mn*****@gmail.comwrote:
__len__() is a built-in function of the list object and is updated along
with the list object elements and will be useful incase the list is very
huge.

len() is an external method again, which may require the processing cycles
again.
The purpose of obj.__len__() is to implement len(obj), which simply
calls it. So obj.__len__() may be faster, but only marginally. The
reason to prefer len(obj) is that if you inadvertently pass an object
that does not implement __len__, you get the more appropriate
TypeError rather than an AttributeError.
Jun 27 '08 #3
Ian Kelly schrieb:
The purpose of obj.__len__() is to implement len(obj), which simply
calls it. So obj.__len__() may be faster, but only marginally. The
reason to prefer len(obj) is that if you inadvertently pass an object
that does not implement __len__, you get the more appropriate
TypeError rather than an AttributeError.
len(obj) is faster than obj.__len__() for several types like str. In
general len() is as least as fast __len__(). len() also does some extra
sanity checks.

python2.5 -m timeit "'abc'.__len__()"
1000000 loops, best of 3: 0.453 usec per loop

python2.5 -m timeit "len('abc')"
1000000 loops, best of 3: 0.292 usec per loop

Common code paths are already highly optimized. Don't try to be clever
unless you really understand what happens inside the interpreter. The
__internal__ methods are called magic methods for a reason. ;)

Christian

Jun 27 '08 #4
"Ian Kelly" <ia*********@gmail.comwrites:
On Tue, May 13, 2008 at 5:57 PM, Nikhil <mn*****@gmail.comwrote:
> __len__() is a built-in function of the list object and is updated along
with the list object elements and will be useful incase the list is very
huge.

len() is an external method again, which may require the processing cycles
again.

The purpose of obj.__len__() is to implement len(obj), which simply
calls it. So obj.__len__() may be faster, but only marginally.
Have you tried it? __len__ is in fact marginally slower because it
involves a dict lookup, whereas the built-in len() knows how to cheat
and invoke __len__ through a slot in the C type struct very
efficiently.

$ python -m timeit -s 'l=[1, 2, 3]' 'len(l)'
1000000 loops, best of 3: 0.24 usec per loop
$ python -m timeit -s 'l=[1, 2, 3]' 'l.__len__()'
1000000 loops, best of 3: 0.347 usec per loop
Jun 27 '08 #5
On Wed, May 14, 2008 at 1:01 AM, Hrvoje Niksic <hn*****@xemacs.orgwrote:
Have you tried it? __len__ is in fact marginally slower because it
involves a dict lookup, whereas the built-in len() knows how to cheat
and invoke __len__ through a slot in the C type struct very
efficiently.

$ python -m timeit -s 'l=[1, 2, 3]' 'len(l)'
1000000 loops, best of 3: 0.24 usec per loop
$ python -m timeit -s 'l=[1, 2, 3]' 'l.__len__()'
1000000 loops, best of 3: 0.347 usec per loop
For built-in types, sure. For user-defined types in Python, it's the
other way around:
>>setup = 'class L:\n def __len__(self): return 42\nl = L()'
t1 = timeit.Timer('len(l)', setup)
t2 = timeit.Timer('l.__len__()', setup)
t1.timeit()
0.63981378918270337
>>t2.timeit()
0.41051271879526041
Jun 27 '08 #6
"Ian Kelly" <ia*********@gmail.comwrites:
On Wed, May 14, 2008 at 1:01 AM, Hrvoje Niksic <hn*****@xemacs.orgwrote:
> Have you tried it? __len__ is in fact marginally slower because it
involves a dict lookup, whereas the built-in len() knows how to cheat
and invoke __len__ through a slot in the C type struct very
efficiently.

$ python -m timeit -s 'l=[1, 2, 3]' 'len(l)'
1000000 loops, best of 3: 0.24 usec per loop
$ python -m timeit -s 'l=[1, 2, 3]' 'l.__len__()'
1000000 loops, best of 3: 0.347 usec per loop

For built-in types, sure.
Well, he did ask about list. :-)
For user-defined types in Python, it's the other way around:
Yes, in that case the C slot contains a generic wrapper that still has
to locate and call the Python function, which ends up being slower.
The point is that such microoptimizations rarely make a difference,
and even then the difference can be counterintuitive, as in the list
example.
Jun 27 '08 #7
Christian Heimes wrote:
Ian Kelly schrieb:
>The purpose of obj.__len__() is to implement len(obj), which simply
calls it. So obj.__len__() may be faster, but only marginally. The
reason to prefer len(obj) is that if you inadvertently pass an object
that does not implement __len__, you get the more appropriate
TypeError rather than an AttributeError.

len(obj) is faster than obj.__len__() for several types like str. In
general len() is as least as fast __len__(). len() also does some extra
sanity checks.

python2.5 -m timeit "'abc'.__len__()"
1000000 loops, best of 3: 0.453 usec per loop

python2.5 -m timeit "len('abc')"
1000000 loops, best of 3: 0.292 usec per loop

Common code paths are already highly optimized. Don't try to be clever
unless you really understand what happens inside the interpreter. The
__internal__ methods are called magic methods for a reason. ;)

Christian
Thanks for the useful insight.
Then why to have __len__() internal method at all when the built-in
len() is faster?
I heard, in Python3, this internal method is being pruned/renamed to
something else? Can someone please shed light here?

Thanks. Nikhil
Jun 27 '08 #8
Nikhil <mn*****@gmail.comwrote:
Then why to have __len__() internal method at all when the built-in
len() is faster?
Because the internal method is used internally.

The idea is that you define __len__() on your objects when appropriate. You
are not expected to ever call it.
Jun 27 '08 #9

"Nikhil" <mn*****@gmail.comwrote in message
news:g0**********@registered.motzarella.org...
| Then why to have __len__() internal method at all when the built-in
| len() is faster?

Nearly all syntax constructions and builtin functions are implemented by
calling one or another of the __special__ methods. This is what makes
Python code so generic and plugging your own classes into the system so
easy.

For example, collection[key] = value is implemented by calling
collection.__setitem__(key, value). When you define a class with that
method, that syntax will work with its instances just the same as for
builtin classes.

Similarly, a+b is implemented by calling a.__add__(b). So if a class
defines __add__, you can 'add' its instances (whatever 'add' means for that
class) with '+'.

(The fact that an *implementation* may followup the 'as if' rule and
optimize operations for certain classes by combining steps does not negate
the *language* rules given above.)

tjr

Jun 27 '08 #10
On May 14, 11:07 am, Nikhil <mnik...@gmail.comwrote:
Christian Heimes wrote:
Ian Kelly schrieb:
The purpose of obj.__len__() is to implement len(obj), which simply
calls it. So obj.__len__() may be faster, but only marginally. The
reason to prefer len(obj) is that if you inadvertently pass an object
that does not implement __len__, you get the more appropriate
TypeError rather than an AttributeError.
len(obj) is faster than obj.__len__() for several types like str. In
general len() is as least as fast __len__(). len() also does some extra
sanity checks.
python2.5 -m timeit "'abc'.__len__()"
1000000 loops, best of 3: 0.453 usec per loop
python2.5 -m timeit "len('abc')"
1000000 loops, best of 3: 0.292 usec per loop
Common code paths are already highly optimized. Don't try to be clever
unless you really understand what happens inside the interpreter. The
__internal__ methods are called magic methods for a reason. ;)
Christian

Thanks for the useful insight.
Then why to have __len__() internal method at all when the built-in
len() is faster?
I heard, in Python3, this internal method is being pruned/renamed to
something else? Can someone please shed light here?
My advice is to think of len() as an operator. Like other operators,
it can be overloaded using the __opname__ syntax:

-x calls x.__neg__
x+2 calls x.__add__
len(x) calls x.__len__

It's not really an operator: it's a regular built-in function, has no
special syntax, and no opcodes associated with it, but in sometimes it
helps to think of it as one.
Carl Banks
Jun 27 '08 #11

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

Similar topics

3
by: Simon | last post by:
Hi, I'm hoping you could show me examples of how a functional/declarative language could be used to consicely describe resticted subsets of elements. I'm looking for a 'specification' style...
4
by: Bart Nessux | last post by:
New to Python... trying to figure out how to count the objects in a list and then map the count to the objects or convert the list to a dict... I think the latter would be better as I need a number...
15
by: les_ander | last post by:
Hi, I have many set objects some of which can contain same group of object while others can be subset of the other. Given a list of sets, I need to get a list of unique sets such that non of the...
15
by: David Bear | last post by:
I've googled for the above and get way too many hits.. I'm looking for an 'easy' way to have the last item in a list returned. I've thought about list but thought there would be a more...
22
by: David Isaac | last post by:
Newbie question: I have been generally open to the proposal that list comprehensions should replace 'map', but I ran into a need for something like map(None,x,y) when len(x)>len(y). I cannot...
19
by: William Wisnieski | last post by:
Hello Everyone, I have a main form with a datasheet subform that I use to query by form. After the user selects two criteria on the main form and clicks the cmdShowResults button on the main...
32
by: Robin Becker | last post by:
Is there some smart/fast way to flatten a level one list using the latest iterator/generator idioms. The problem arises in coneverting lists of (x,y) coordinates into a single list of...
26
by: Swroteb | last post by:
Hi there, I've got a reasonably sized list of objects that I'd like to pull out all combinations of five elements from. Right now I have a way to do this that's quite slow, but manageable. I...
16
by: Michael M. | last post by:
How to find the longst element list of lists? I think, there should be an easier way then this: s1 = s2 = s3 = if len(s1) >= len(s2) and len(s1) >= len(s3): sx1=s1 ## s1 ist längster
10
by: marcstuart | last post by:
How do I divide a list into a set group of sublist's- if the list is not evenly dividable ? consider this example: x = y = 3 # number of lists I want to break x into z = y/x what I...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...

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.