Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Do Python Lists keep a count for len() or does it count for each call?

Tags:

python

If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?

like image 725
PKKid Avatar asked Mar 30 '09 21:03

PKKid


People also ask

Do Python lists store their length?

Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.

How do you count a list in Python?

The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.

How do you count how many times something appears in a list in Python?

Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.

How many items are in a list Python?

If a two-dimensional list (a list of lists) is passed directly to len() , the number of lists stored as elements is returned. The number of items in each list (the number of items in each row) can be obtained using the list comprehensions. The total number of items can be calculated with sum() .


1 Answers

Don't worry: Of course it saves the count and thus len() on lists is a pretty cheap operation. Same is true for strings, dictionaries and sets, by the way!

like image 173
Ferdinand Beyer Avatar answered Sep 28 '22 06:09

Ferdinand Beyer