What is the name of the function that returns the number of values in a 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

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

Python List count[] is an inbuilt function in Python that returns the count of how many times a given object occurs in a List. The count[] function is used to count elements on a list as well as a string.

Syntax:

list_name.count[object]

Parameters:

The object is the things whose count is to be returned.



Returns:

count[] method returns the count of how many times object occurs in the list.

Exception:

If more then 1 parameter is passed in count[] method, it returns a TypeError.

Example 1: Use of count[]

Python3




# Python3 program to count the number of times
# an object appears in a list using count[] method
list1 = [1, 1, 1, 2, 3, 2, 1]
# Counts the number of times 1 appears in list1
print[list1.count[1]]
list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']
# Counts the number of times 'b' appears in list2
print[list2.count['b']]
list3 = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat']
# Counts the number of times 'Cat' appears in list3
print[list3.count['Cat']]

Output:

4 3 2

Example 2: TypeError

Python3




# Python3 program to demonstrate
# the error in count[] method
list1 = [1, 1, 1, 2, 3, 2, 1]
# Error when two parameters is passed.
print[list1.count[1, 2]]

Output:

Traceback [most recent call last]: File "/home/41d2d7646b4b549b399b0dfe29e38c53.py", line 7, in print[list1.count[1, 2]] TypeError: count[] takes exactly one argument [2 given]

Example 3: Count Tuple and List Elements Inside List

Python3




# Python3 program to count the number of times
# an object appears in a list using count[] method
list1 = [ ['Cat', 'Bat'], ['Sat', 'Cat'], ['Cat', 'Bat'],
['Cat', 'Bat', 'Sat'], [1, 2], [1, 2, 3], [1, 2] ]
# Counts the number of times 'Cat' appears in list1
print[list1.count[['Cat', 'Bat']]]
# Count the number of times sublist
# '[1, 2]' appears in list1
print[list1.count[[1, 2]]]

Output:

2 2

Practical Application

Let’s say we want to count each element in a list and store it in another list or say dictionary.

Python3




# Python3 program to count the number of times
# an object appears in a list using count[] method
lst = ['Cat', 'Bat', 'Sat', 'Cat', 'Mat', 'Cat', 'Sat']
# To get the number of occurrences
# of each item in a list
print [[ [l, lst.count[l]] for l in set[lst]]]
# To get the number of occurrences
# of each item in a dictionary
print [dict[ [l, lst.count[l] ] for l in set[lst]]]

Output:

[['Mat', 1], ['Cat', 3], ['Sat', 2], ['Bat', 1]] {'Bat': 1, 'Cat': 3, 'Sat': 2, 'Mat': 1}

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-Built-in-functions
python-list
python-list-functions
Practice Tags :
python-list
Read Full Article

What do you want to do?

  • Look up values vertically in a list by using an exact match

  • Look up values vertically in a list by using an approximate match

  • Look up values vertically in a list of unknown size by using an exact match

  • Look up values horizontally in a list by using an exact match

  • Look up values horizontally in a list by using an approximate match

  • Create a lookup formula with the Lookup Wizard [Excel 2007 only]

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.

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.

Introduction

In Python, you’ll be able to use a list function that creates a group that will be manipulated for your analysis. This collection of data is named a list object.

While all methods are functions in Python, not all functions are methods. There’s a key difference between functions and methods in Python. Functions take objects as inputs while Methods in contrast act on objects.

Image Source: Google Images

Python offers the subsequent list functions:

  • sort[]: Sorts the list in ascending order.
  • type[list]: It returns the class type of an object.
  • append[]: Adds one element to a list.
  • extend[]: Adds multiple elements to a list.
  • index[]:Returns the first appearance of a particularvalue.
  • max[list]: It returns an item from the list with a max value.
  • min[list]: It returns an item from the list with a min value.
  • len[list]: It gives the overall length of the list.
  • clear[]: Removes all the elements from the list.
  • insert[]:Adds a component at the required position.
  • count[]:Returns the numberof elements with the required value.
  • pop[]:Removes the element at the required position.
  • remove[]:Removes the primary item with the desired value.
  • reverse[]:Reverses the order of the list.
  • copy[]: Returns a duplicate of the list.

Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề