[Tutor] counting a list of elements

Knacktus knacktus at googlemail.com
Fri Apr 1 20:04:13 CEST 2011


Am 01.04.2011 19:16, schrieb Karim:
>
>
> Hello,
>
> I would like to get advice on the best practice to count elements in a
> list (built from scractch).

It's not clear to me what your starting point is.

If you don't have a list and don't need a list, but have a large number 
of objects you create in your code sequentially or a large number of 
other events and you want to know how many of those objects exist / 
events have occured, then simply use a counter while creating.

If you have a list (for whatever reason), then use len().

HTH,

Jan

> The number of elements is in the range 1e3 and 1e6.
>
> 1) I could create a generator and set a counter (i +=1) in the loop.
>
> 2) or simply len(mylist).
>
> I don't need the content of the list, indeed, in term of memory I don't
> want to wast it. But I suppose len() is optimized too (C impementation).
>
> If you have some thought to share don't hesitate.
>
> Karim
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list