473,574 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6543
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*********@gm ail.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('l en(l)', setup)
t2 = timeit.Timer('l .__len__()', setup)
t1.timeit()
0.6398137891827 0337
>>t2.timeit()
0.4105127187952 6041
Jun 27 '08 #6
"Ian Kelly" <ia*********@gm ail.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 microoptimizati ons rarely make a difference,
and even then the difference can be counterintuitiv e, 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.m otzarella.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.__se titem__(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

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

Similar topics

3
7523
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 definition so any ideas/input would be very welcome. Thanks for your time, Simon. --
4
2954
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 associated with each entry. Any pointers? Also, does this bit of code look to be truely random? def random_number_gen(): winner = ...
15
2180
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 set is an subset of another or contain exactly the same members. Tried to do the following: s1=set() s2=set() s3=set()
15
3635
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 gracefull way.
22
1876
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 it seems use 'zip' because I'll lose info from x. How do I do this as a list comprehension? (Or, more generally, what is the best way to do this...
19
3522
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 form, the subform returns the records based on the two criteria. The criteria used on the main form are values selected in two list boxes. When the...
32
2763
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 coordinates eg f() --> or g(,) -->
26
2184
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 know there must be a better way to do this, but I'm not sure what it is. Here's what I've got so far: for a in myList: for b in myList:
16
2581
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
1406
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 would like to get is 3 sublists
0
7719
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7808
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6450
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5616
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5299
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3739
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3749
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1335
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.