Total number of elements in list Python

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 List count[]

The count[] is a built-in function in Python. It will return you the count of a given element in the list.

Syntax:

list.count[element]

Parameters:

element: The element you want to find the count.

ReturnValue:

The count[] method will return an integer value, i.e., the count of the given element from the given list. It returns a 0 if the value is not found in the given list.

Example 1: List Count

Following example shows the working of count[] function on a list:

list1 = ['red', 'green', 'blue', 'orange', 'green', 'gray', 'green'] color_count = list1.count['green'] print['The count of color: green is ', color_count]

Output:

The count of color: green is 3

Example 2: Find the count of elements [Duplicates] in a givenlist

list1 = [2,3,4,3,10,3,5,6,3] elm_count = list1.count[3] print['The count of element: 3 is ', elm_count]

Output:

The count of element: 3 is 4

Summary:

  • The count[] is a built-in function in Python. It will return you the count of a given element in a list or a string.
  • In the case of a list, the element to be counted needs to be given to the count[] function, and it will return the count of the element.
  • The count[] method returns an integer value.

Last updated on Dec 21,2021 800.9K Views

The list in Python is a collection data-type that is ordered and changeable. A list can have duplicate entry as well. The Python len[] method is used to find the length of any object. In this article, we will learn how to find the length of list in python in the following sequence:

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.

There are two most commonly used and basic methods that are used to find the length of the list in Python:

  • Len[] Method
  • Naive Method

Len[] Method

There is a built-in function called len[] for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len[] method takes an argument where you may provide a list and it returns the length of the given list.

The len[] method is one of the most used and convenient ways to find the length of list in Python. This is the most conventional technique adopted by all the programmers today.

Find out our Python Training in Top Cities/Countries

Syntax:

len[list]

The List parameter is a list for which the number of elements are to be counted. It returns the number of elements in the list.

Example:

ListName = ["Hello", "Edureka", 1, 2, 3] print ["Number of items in the list = ", len[ListName]]

Output:5

Naive Method

The len[] method is the most commonly used method to find the length of the list in Python. But there is another basic method that provides the length of the list.

In the Naive method, one just runs a loop and increases the counter until the last element of the list to know its count. This is the most basic strategy that can be used in the absence of other efficient techniques.

Example:

ListName = [ "Hello", "Edureka", 1,2,3 ] print ["The list is : " + str[ListName]] counter = 0 for i in ListName: counter = counter + 1 print ["Length of list using naive method is : " + str[counter]]

Output:

The list is : ["Hello", "Edureka", 1,2,3] Length of list using naive method is : 5

This was all about finding the length of list in Python. The len[] method is the most popular method. Whereas, you can also use the basic method of finding the length with the help of Naive Method.

With this, we have come to the end of our article. I hope you understood how to find the length of any list in Python.

To get in-depth knowledge of Python along with its various applications, you can enroll for live Python Certification Training with 24/7 support and lifetime access. 

Got a question for us? Please mention it in the comments section of this “Length of List in Python” blog and we will get back to you as soon as possible or join our Python Training in Jeddah.

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

The syntax of the count[] method is:

list.count[element]

count[] Parameters

The count[] method takes a single argument:

  • element - the element to be counted

Return value from count[]

The count[] method returns the number of times element appears in the list.

Example 1: Use of count[]

# vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# count element 'i' count = vowels.count['i']

# print count print['The count of i is:', count]

# count element 'p' count = vowels.count['p']

# print count print['The count of p is:', count]

Output

The count of i is: 2 The count of p is: 0

Example 2: Count Tuple and List Elements Inside List

# random list random = ['a', ['a', 'b'], ['a', 'b'], [3, 4]]

# count element ['a', 'b'] count = random.count[['a', 'b']]

# print count print["The count of ['a', 'b'] is:", count]

# count element [3, 4] count = random.count[[3, 4]]

# print count print["The count of [3, 4] is:", count]

Output

The count of ['a', 'b'] is: 2 The count of [3, 4] is: 1

len[]

it will count the element in the list, tuple and string and dictionary, eg.

>>> mylist = [1,2,3] #list >>> len[mylist] 3 >>> word = 'hello' # string >>> len[word] 5 >>> vals = {'a':1,'b':2} #dictionary >>> len[vals] 2 >>> tup = [4,5,6] # tuple >>> len[tup] 3

To learn Python you can use byte of python , it is best ebook for python beginners.

In Python, the built-in function len[] is used to get the length [the number of items] of a list.

  • Built-in Functions - len[] — Python 3.9.7 documentation

This article describes the following contents.

  • Get the number of items in a list with len[]
  • For two-dimensional lists [lists of lists]
  • For multidimensional lists

See the following article for the usage of len[] for objects of other types.

  • How to use len[] in Python

You can get the total number of elements with len[]. If you want to get the number of occurrences of an element, use the count[] method or Counter of the standard library collections.

  • Count elements from a list with collections.Counter in Python

Get the number of items in a list with len[]

By passing a list as an argument of the built-in function len[], its number of items is returned as an integer value.

l = [0, 1, 2, 3] print[len[l]] # 4

For two-dimensional lists [lists of lists]

If a two-dimensional list [a list of lists] is passed directly to len[], the number of lists stored as elements is returned.

l_2d = [[0, 1, 2], [3, 4, 5]] print[len[l_2d]] # 2

The number of items in each list [the number of items in each row] can be obtained using the list comprehensions.

  • List comprehensions in Python

print[[len[v] for v in l_2d]] # [3, 3]

The total number of items can be calculated with sum[].

A generator version of the list comprehensions [= generator expressions] is used here. Generator expressions are enclosed in [], not [], but when they are used within [], as in this example, it is not necessary to write [] twice, and [] of generator expressions can be omitted.

print[sum[len[v] for v in l_2d]] # 6

If NumPy is installed in your environment, you can convert it to a NumPy array ndarray.

You can get the total number of items with the attribute size, and the shape [number of rows and columns] with the attribute shape.

import numpy as np l_2d = [[0, 1, 2], [3, 4, 5]] arr_2d = np.array[l_2d] print[arr_2d] # [[0 1 2] # [3 4 5]] print[arr_2d.size] # 6 print[arr_2d.shape] # [2, 3]

For multidimensional lists

Take as an example a list whose elements are lists of varying sizes.

If this is passed to len[], the number of objects stored as elements is returned.

l_multi = [[0, 1, 2, [10, 20, 30]], [3, 4, 5], 100] print[len[l_multi]] # 3

Also, if you pass it to numpy.array[], a NumPy array ndarray whose elements are list type objects with varying numbers of elements is generated. size and shape are also calculated for objects stored as elements.

arr_multi = np.array[l_multi] print[arr_multi] # [list[[0, 1, 2, [10, 20, 30]]] list[[3, 4, 5]] 100] print[arr_multi.size] # 3 print[arr_multi.shape] # [3,]

To get the total number of elements in a list that stores lists of varying sizes, you can define a function that recursively calculates the number of elements in the list.

def my_len[l]: count = 0 if isinstance[l, list]: for v in l: count += my_len[v] return count else: return 1 l_multi = [[0, 1, 2, [10, 20, 30]], [3, 4, 5], 100] print[my_len[l_multi]] # 10 l_2d = [[0, 1, 2], [3, 4, 5]] print[my_len[l_2d]] # 6 l = [0, 1, 2, 3] print[my_len[l]] # 4

Video liên quan

Chủ Đề