Python Sorting List Elements

Python provides the sort() method to sort the elements of a list. This method can be used as:


x.sort()


This will sort the list 'x' into ascending order. If we want to sort the elements of the list into descending order, then we can mention 'reverse=True' in the sort() method as:


x.sort(reverse=True)


Number of Occurrences of an Element in the List:

Python provides count() method that returns the number of times a particular element is repeated in the list. For example,


n = x.count(y)

will return the number of times 'y' is found in the list 'x'. This method return 0 if the element is not found in the list.


Finding Common Elements in Two Lists :

Sometimes, it is useful to know which elements are repeated in two lists. For example, there is a scholarship for which a group of students enrolled in a college. There is another scholarship for which another group of students got enrolled. Now, we want to know the names of the students who enrolled for both the scholarships so that we can restrict them to take only one scholarship. That means, we are supposed to find out the common students (or elements) in both the lists.

Let's take the two groups of students as two lists. First of all, we should convert the lists into sets, using set() function, as:

set(list)

set1.intersection(set2)


This method returns a set that contains common or repeated elements in the two sets. This gives us the names of the students who are found in both the sets.


A Python program to find common elements in two lists.


Storing Different Types of Data in a List

The beauty of lists is that they can store different types of elements. For example, we can store an integer, a string a float type number etc. in the same string. It is also possible to retrieve the elements from the list. This has advantage for lists over arrays. We can create list 'emp' as an empty list as:


emp = []


Then we can store employee data like id number, name and salary details into the 'emp' list using the append() method. After that, it is possible to retrieve employee details depending on id number of the employee.

A Python program to create a list with employee data and then retrieve a particular employee details.