Advanced Python List Methods and Techniques - GeeksforGeeks

22 Sep, 2021
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.
Lists are one of the most powerful tools in python. They have a lot of hidden tricks which makes them extremely versatile. Let’s explore some of these useful techniques which make our lives much easier !!!
To sort a list in ascending or descending order, we use the sort() function with the following syntax:
For ascending order: 
list.sort()
For descending order: 
list.sort(reverse=True)
Example:
Python3
# sorting a list using sort() function my_list = [5, 2, 90, 24, 10]  # sorting in ascending order it permanently# changes the order of the listmy_list.sort()print(my_list) # sorting in descending order it permanently# changes the order of the listmy_list.sort(reverse=True)print(my_list)
Output:
[2, 5, 10, 24, 90]
[90, 24, 10, 5, 2]
To temporarily change the order of the list use the sorted() function with the syntax: 
list.sorted()
Python3
# temporary sorting using sorted() method my_list = [5, 2, 90, 24, 10] # ascending orderprint(sorted(my_list)) # descending ordermy_list_2 = sorted(my_list)print(my_list)
Output:
[2, 5, 10, 24, 90]
[5, 2, 90, 24, 10]
To reverse the order of a list we use the reverse() function. Its syntax is:
list.reverse()
Example:
Python3
# reverse a list using reverse() my_list = [5, 2, 90, 24, 10] # reversemy_list.reverse()print(my_list)
Output:
[10, 24, 90, 2, 5]
Or we could apply list comprehension to reverse a list:
 list = list[::-1]
Example:
Python3
# reverse using list comprehensionmy_list = [5, 2, 90, 24, 10] # reverseprint(my_list[::-1])
Output:
[10, 24, 90, 2, 5]
As dictionaries in python do not contain duplicate keys. We use the dict.fromkeys() function to convert our list into a dictionary with list elements as keys. And then we convert the dictionary back to list. 
This is a powerful trick to automatically remove all the duplicates. Its syntax is:
My_list =[‘a’, ’b’, ’c’, ’b’, ’a’]
Mylist = list(dict.fromkeys(My_List))
Example:
Python3
# removing duplicates from a list using dictionaries my_list_1 = [5, 2, 90, 24, 10, 2, 90, 34]my_list_2 = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] # removing duplicates from list 1my_list_1 = list(dict.fromkeys(my_list_1))print(my_list_1) # removing duplicates from list 2my_list_2 = list(dict.fromkeys(my_list_2))print(my_list_2)
Output:
[5, 2, 90, 24, 10, 34]
['a', 'b', 'c', 'd', 'e']
Python lists can be filtered with the help of filter() function or with the help of list comprehension. Below is the syntax:
My_list = list(filter(filter_function , iterable_item))
The Filter function returns an iterator object which we must convert back into the list.
Example:
Python3
# filtering with the help of filter() function# creating a filter function filter all the values less than 20 # filter functiondef my_filter(n):    if n > 20:        return n        # driver codeif __name__ == "__main__":    my_list = [5, 2, 90, 24, 10, 2, 95, 36]    my_filtered_list = list(filter(my_filter, my_list))    print(my_filtered_list)
Output:
[90, 24, 95, 36]
We can also filter using list comprehension. It is a much easier and elegant way to filter lists, below is the syntax:
My_list = [item for item in my_list if (condition)]
Example:
Python3
# filtering with the help of list comprehensionmy_list = [5, 2, 90, 24, 10, 2, 95, 36] # an elegant way to sort the listmy_list = [item for item in my_list if item > 20]print(my_list)
Output:
[90, 24, 95, 36]
To modify the values in the list with the help of an external function, we make use of the map() function. Map() function returns a map object (iterator) of the results after applying the given function to each element of a given iterable(list, tuple etc.). Below is the syntax:
My_list = list(map(function,iterable))
Example:
Python3
# using map() function to modify the textdef squaring(n):    return n**2 # driver codeif __name__ == "__main__":    my_list = [5, 2, 90, 24, 10, 2, 95, 36]     my_squared_list = list(map(squaring, my_list))    print(my_squared_list)
Output:
[25, 4, 8100, 576, 100, 4, 9025, 1296]
A much cleaner approach is using list comprehension.
Example:
Python3
# the same result can be obtained by a much pythonic approach# i.e., by using list comprehensionmy_list = [5, 2, 90, 24, 10, 2, 95, 36] print([i**2 for i in my_list])
Output:
[25, 4, 8100, 576, 100, 4, 9025, 1296]
We can even combine lists with the help of the zip() function which results in a list of tuples. Here each item from list A is combined with corresponding elements from list B in the form of a tuple. Below is the syntax:
My_list = zip(list_1, list_2)
Example:
Python3
# combing lists with the help of zip() functionmy_list_1 = [5, 2, 90, 24, 10]my_list_2 = [6, 3, 91, 25, 12] # combinedmy_combined_list = list(zip(my_list_1, my_list_2))print(my_combined_list)
Output:
[(5, 6), (2, 3), (90, 91), (24, 25), (10, 12)]
To find the most frequent element we make use of the set() function. The set() function removes all the duplicates from the list, and the max() function returns the most frequent element (which is found with the help of ‘key’). The key is an optional single argument function. Below is the syntax:
Most_frequent_value =max(set(my_list),key=mylist.count)
Example :
Python3
# to find the most frequent element from the listmy_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] most_frequent_value = max(set(my_list), key=my_list.count) print("The most common element is:", most_frequent_value)
Output:
The most common element is: a
To check whether an item exists in a list, we use the in statement. 
Example:
Python3
my_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e'] # to check whether 'c' is a member of my_list# returns true if presentprint('c' in my_list)  # to check whether 'f' is a member of my_list# returns false if not presentprint('f' in my_list)
Output:
True
False
Sometimes we encounter a list where each element in itself is a list. To convert a list of lists into a single list, we use list comprehension.
my_list = [item  for List in list_of_lists for item in List ]
Example:
Python3
# to flatten a list_of_lists by using list comprehensionlist_of_lists = [[1, 2],                 [3, 4],                 [5, 6],                 [7, 8]] # using list comprehensionmy_list = [item for List in list_of_lists for item in List]print(my_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
sweetyty
anikaseth98
python-list
Technical Scripter 2020
Python
Technical Scripter
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()