Which of the following functions will return the total number of elements in a list?

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']

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.

9. Lists¶

A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type. Lists and strings — and other things that behave like ordered sets — are called sequences.

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.

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.

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.

Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề