Which method of list will return the number of elements in the list?

Python List count()

In this tutorial, we will learn about the Python List count() method with the help of examples.

The count() method returns the number of times the specified element appears in the list.

Example

# create a list numbers = [2, 3, 5, 2, 11, 2, 7]
# check the count of 2 count = numbers.count(2)
print('Count of 2:', count) # Output: Count of 2: 3

Explanation

Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.

Lists and other similar builtin objects with a "size" in Python, in particular, have an attribute called ob_size, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.

But if you're checking if list size is zero or not, don't use len - instead, put the list in a boolean context - it treated as False if empty, True otherwise.

len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

len is implemented with __len__, from the data model docs:

object.__len__(self)

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __nonzero__() [in Python 2 or __bool__() in Python 3] method and whose __len__() method returns zero is considered to be false in a Boolean context.

And we can also see that __len__ is a method of lists:

items.__len__()

returns 3.

Count elements in a flat list

Suppose we have a list i.e.

# List of strings listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']
To count the elements in this list, we have different ways. Let’s explore them,

Use len() function to get the size of a list

Python provides a inbuilt function to get the size of a sequence i.e.

len(s)
Arguments:
  • s : A sequence like object like, list, string, bytes, tuple etc.

It returns the length of object i.e. count of elements in the object.

Advertisements

Now let’s use this len() function to get the size of a list i.e.

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test'] # Get size of a list using len() length = len(listOfElems) print('Number of elements in list : ', length)
Output:
Number of elements in list : 9
How does len() function works ?

When len(s) function is called, it internally calls the __len__() function of the passed object s. Default sequential containers like list, tuple & string has implementation of __len__() function, that returns the count of elements in that sequence.

So, in our case we passed the list object to the len() function. Which internally called the __len__() of the list object, to fetch the count of elements in list.

Use list.__len__() to count elements in a list

We can directly call the __len__() member function of list to get the size of list i.e.

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test'] # Get size of a list using list.__len__() length = listOfElems.__len__() print('Number of elements in list : ', length)
Output:
Number of elements in list : 9
Although we got the size of list using __len__() function. It is not a recommended way, we should always prefer len() to get the size of list.

List in Python

A list in Python is implemented to store the sequence of various types of data. However, there are six data types in Python that are capable of storing the sequences but the most common and reliable type is a list. To learn more about python you can join our Master Python programming course.

A list is defined as a collection of values or items of different types. The items in the list are separated with a comma (,) and enclosed with the square brackets [].

It is defined as follows:

list1 = ['edureka', 'python', 2019]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];

If you want to learn Artificial Intelligence and Machine Learning in-depth, come to us and sign up for this Post Graduate Diploma AI and ML courses.

How to Get the Number of Elements in a Python List?

In this article, we will discuss how to get the number of elements in a Python List.

Examples:

Input: [1,2,3,4,5]

Output:
No of elements in the list are
5

Input: [1.2 ,4.5, 2.2]



Output:
No of elements in the list are
3

Input: [“apple”, “banana”, “mangoe”]

Output:
No of elements in the list are
3

Before getting the Number of Elements in the Python List we have to create an empty List. After creating an empty list we have to insert the items or elements into the list. There are two methods to get the number of elements in the list i.e,

  • Using Len( ) function
  • Using for loop

Using Len() function

We can use the len function i.e len( ) to return the number of elements present in the list

Python3




# Returning the number of elements using
# len() function in python
list = [] # declare empty list
# adding items or elements to the list
list.append(1)
list.append(2)
list.append(3)
list.append(4)
# printing the list
print(list)
# using the len() which return the number
# of elements in the list
print("No of elements in list are")
print(len(list))
Output [1, 2, 3, 4] No of elements in list are 4

Using for loop

We can declare a counter variable to count the number of elements in the list using a for loop and print the counter after the loop gets terminated.

Python3




# Python Program for returning the number
# of elements in the list using for loop
list = [] # declaring empty list
# inserting elements in the list using
# append method
list.append(1)
list.append(2)
list.append(3)
list.append(4)
# declaring count variable as integer to keep
# track of the number of elements in for loop
count = 0
# for loop for iterating through each element
# in the list
for i in list:
# increments count variable for each
# iteration
count = count+1
# prints the count variable i.e the total number
# of elements in the list
print(list)
print("No of elements in the list are")
print(count)
Output [1, 2, 3, 4] No of elements in the list are 4

Hence, in this way, we can return the number of elements of a list in python using for loop.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python Programs
Python list-programs
Read Full Article

sort() method

The sort() method is a built-in Python method that, by default, sorts the list in ascending order. However, you can modify the order from ascending to descending by specifying the sorting criteria.

Example

Let's say you want to sort the element in prices in ascending order. You would type prices followed by a . (period) followed by the method name, i.e., sort including the parentheses.

prices = [238.11, 237.81, 238.91] prices.sort() print(prices) [237.81, 238.11, 238.91]

type() function

For the type() function, it returns the class type of an object.

Example

Here we will see what type of both fam and fam2 are:

fam = ["liz", 1.73, "emma", 1.68, "mom", 1.71, "dad", 1.89] fam ['liz', 1.73, 'emma', 1.68, 'mom', 1.71, 'dad', 1.89]

Let's see what the type of the object is:

type(fam) list

Now, let's look at fam2.

fam2 = [["liz", 1.73], ["emma", 1.68], ["mom", 1.71], ["dad", 1.89]] fam2 [['liz', 1.73], ['emma', 1.68], ['mom', 1.71], ['dad', 1.89]]

Let's see what the type of the object is:

type(fam2) list

These calls show that both fam and fam2 are in fact lists.

append() method

The append() method will add certain content you enter to the end of the elements you select.

Example

In this example, let’s extend the string by adding “April” to the list with the method append(). Using append() will increase the length of the list by 1.

months = ['January', 'February', 'March'] months.append('April') print(months)

When you run the above code, it produces the following result:

['January', 'February', 'March', 'April']

Python count

The count() is a built-in function in Python. It will return the total count of a given element in a list. The count() function is used to count elements on a list as well as a string.

In this Python tutorial, you will learn:

  • Python count
  • Python List count()
  • Example 1: List Count
  • Example 2: Find the count of elements (Duplicates) in a givenlist

Video liên quan

Postingan terbaru

LIHAT SEMUA