0% found this document useful (0 votes)
6 views10 pages

Module 1: Advanced Python List Methods and Techniques

The document outlines advanced methods and techniques for manipulating lists in Python, including sorting, reversing, eliminating duplicates, filtering, and modifying list elements. It provides examples of using functions like sort(), reverse(), filter(), map(), and zip() to perform various operations on lists. Additionally, it discusses checking for membership, flattening nested lists, and identifying the most frequent item in a list.

Uploaded by

Edrian Rodriguez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views10 pages

Module 1: Advanced Python List Methods and Techniques

The document outlines advanced methods and techniques for manipulating lists in Python, including sorting, reversing, eliminating duplicates, filtering, and modifying list elements. It provides examples of using functions like sort(), reverse(), filter(), map(), and zip() to perform various operations on lists. Additionally, it discusses checking for membership, flattening nested lists, and identifying the most frequent item in a list.

Uploaded by

Edrian Rodriguez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 1

PRELIMS: LISTS METHODS AND TECHNIQUES

Module 1: Advanced Python List Methods and Techniques


Objectives:
- This module aims:
1. To define lists;
2. To enumerate the Python list methods and techniques; and
3. To discuss each method and technique.

In other languages, lists are like dynamically scaled arrays (vectors in C++ and
ArrayLists in Java). Lists are a handy tool in Python because they don't always
have to be homogeneous. Data types such as Strings, Integers, and Objects can
all be found in a single list. Lists can be changed even after they are created
because they are mutable.

One of Python's most useful features is the list. They are incredibly adaptable
due to their many hidden tricks.

Organizing a list
Using the sort() function and the following syntax, we can arrange a list either
in ascending or descending order:

In ascending order:
list.sort()

In descending order:
list.sort(True for reverse)

Example:
Python3
# sorting a list using sort() function

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 2
PRELIMS: LISTS METHODS AND TECHNIQUES

my_list = [5, 2, 90, 24, 10]

# sorting in ascending order permanently


# changes the order of the list
my_list.sort()
print(my_list)

# sorting in descending order permanently


# changes the order of the list
my_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 order
print(sorted(my_list))

# descending order
my_list_2 = sorted(my_list)

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 3
PRELIMS: LISTS METHODS AND TECHNIQUES

print(my_list)

Output:
[2, 5, 10, 24, 90]
[5, 2, 90, 24, 10]
Reversing a list
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]

# reverse
my_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 comprehension
my_list = [5, 2, 90, 24, 10]

# reverse

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 4
PRELIMS: LISTS METHODS AND TECHNIQUES

print(my_list[::-1])

Output:
[10, 24, 90, 2, 5]

Eliminating duplicates
Python dictionaries don't have duplicate keys. To turn our list into a dictionary
using list elements as keys, we utilize the dict.fromkeys() function. The
dictionary is then converted back to a list.

This is an effective method for automatically eliminating duplicates. This is its


syntax:
[‘a’, ‘b’, ‘c’, ‘b’, ‘a’] = My_list
List(dict.fromkeys(My_List)) = Mylist

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 1


my_list_1 = list(dict.fromkeys(my_list_1))
print(my_list_1)

# removing duplicates from list 2


my_list_2 = list(dict.fromkeys(my_list_2))
print(my_list_2)

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 5
PRELIMS: LISTS METHODS AND TECHNIQUES

Output:
[5, 2, 90, 24, 10, 34]
['a', 'b', 'c', 'd', 'e']

Sorting through a list


Both list comprehension and the filter() function can be used to filter Python
lists. The syntax is as follows:
My_list = list(filter(filter_function , iterable_item))
We must transform the iterator object that the Filter method returns back into a
list.

Example:
Python3
# filtering with the help of filter() function
# creating a filter function filter all the values less than 20

# filter function
def my_filter(n):
if n > 20:
return n

# driver code
if __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]

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 6
PRELIMS: LISTS METHODS AND TECHNIQUES

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 comprehension
my_list = [5, 2, 90, 24, 10, 2, 95, 36]

# an elegant way to sort the list


my_list = [item for item in my_list if item > 20]
print(my_list)

Output:
[90, 24, 95, 36]

Changing the list


We utilize the map() function to change the values in the list with the aid of an
external function. After applying the specified function to each element in a
supplied iterable (list, tuple, etc.), the Map() function returns a map object
(iterator) with the results. The syntax is as follows:

My_list = list(map(function,iterable))
Example:
Python3
# using map() function to modify the text
def squaring(n):
return n**2

# driver code
if __name__ == "__main__":

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 7
PRELIMS: LISTS METHODS AND TECHNIQUES

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 comprehension
my_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]

Putting lists together


With the aid of the zip() method, which produces a list of tuples, we can even
merge lists. In this case, every item in list A is joined with matching components
from list B to create a tuple. The syntax is as follows:
My_list = zip(list_1, list_2)
Example:
Python3
# combing lists with the help of zip() function
my_list_1 = [5, 2, 90, 24, 10]
my_list_2 = [6, 3, 91, 25, 12]

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 8
PRELIMS: LISTS METHODS AND TECHNIQUES

# combined
my_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)]

Identifying the most prevalent item


We utilize the set() function to determine which element occurs most
frequently. The max() function returns the most frequent entry (located with the
aid of "key"), whereas the set() function eliminates all duplicates from the list.
An optional one argument function serves as the key. The syntax is as follows:

Most_frequent_value =max(set(my_list),key=mylist.count)
Example :
Python3
# to find the most frequent element from the list
my_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
Checking for membership in a list
To check whether an item exists in a list, we use the in statement.
Example:
Python3

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 9
PRELIMS: LISTS METHODS AND TECHNIQUES

my_list = ['a', 'a', 'a', 'b', 'c', 'd', 'd', 'e']

# to check whether 'c' is a member of my_list


# returns true if present
print('c' in my_list)

# to check whether 'f' is a member of my_list


# returns false if not present
print('f' in my_list)

Output:
True
False

Flatten a list of lists


We occasionally come across lists where every element is a list in and of itself.
List comprehension is the process of turning a collection of lists into a single
list.

my_list = [item for List in list_of_lists for item in List ]


Example:
Python3
# to flatten a list_of_lists by using list comprehension
list_of_lists = [[1, 2],
[3, 4],
[5, 6],
[7, 8]]

# using list comprehension


my_list = [item for List in list_of_lists for item in List]

Course Module 1
Course Title: MSCS 7101- ADVANCE DATA STRUCTURE 10
PRELIMS: LISTS METHODS AND TECHNIQUES

print(my_list)

Output:
[1, 2, 3, 4, 5, 6, 7, 8]

References:

Geeks for Geeks. 2023. Advanced Python List Methods and Techniques
Retrieved from https://www.geeksforgeeks.org/advanced-python-list-methods-
and-techniques/

Nik Piepenbreier. 2020. Advanced Python List Methods and Techniques


Towards Data Science
Medium
USA

Michael Galarnyk. 2024. Python Lists and List Manipulation, Explained


Data Science
Built In
USA

Course Module 1

You might also like