1. Home
python

Python Tutorials - Elevate Your Coding Skills with Comprehensive Tutorials

Discover Python tutorials covering everything from the basics to advanced topics. Whether you're new to programming or looking to level up your skills, our tutorials will guide you every step of the way

  • 201 Lessons
  • 33 Hours
right-top-arrow

Tutorial Playlist

200 Lessons
26

List Methods in Python

Updated on 19/07/20245,561 Views

Introduction

In Python—a language revered for its versatility—list methods stand out as integral tools for efficient data management. Mastery over these methods translates to significant strides in programming, enabling seamless data manipulation, organization, and retrieval. This tutorial on list methods in Python aims to provide a detailed walkthrough, ensuring professionals harness the full potential of lists, making them indispensable assets in real-world applications and complex projects.

Overview

Lists in Python are the backbone of numerous applications, often compared to dynamic arrays in other languages. Their ability to hold diverse data types, coupled with an array of built-in methods, renders them essential for both beginners and seasoned developers. In this tutorial, we will unravel the layers of Python list methods, focusing on their syntax, usage, and real-world implications. Our intent is to transform your perspective on lists, transitioning from basic understanding to in-depth expertise.

List Methods in Python

In Python, lists are a versatile and commonly used data structure. They are used to store collections of items, and Python provides various methods for manipulating and working with lists. Here are some important functions of the Python list, along with examples of how to use them:

1. append(): Adds an element to the end of the list.

Code:

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)  # Output: ["apple", "banana", "cherry", "orange"]

2. insert(): Inserts an element at a specified position in the list.

Code:

fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange")
print(fruits)  # Output: ["apple", "orange", "banana", "cherry"]

3. remove(): Removes the first occurrence of a specified element from the list.

Code:

fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)  # Output: ["apple", "cherry"]

4. pop(): Removes and returns an element at the specified index. If no index is provided, it removes and returns the last element.

Code:

fruits = ["apple", "banana", "cherry"]
removed_fruit = fruits.pop(1)
print(removed_fruit)  # Output: "banana"

5. index(): Returns the index of the first occurrence of a specified element.

Code:

fruits = ["apple", "banana", "cherry"]
index = fruits.index("cherry")
print(index)  # Output: 2

6. count(): Returns the number of times a specified element appears in the list.

Code:

fruits = ["apple", "banana", "cherry", "banana"]
count = fruits.count("banana")
print(count)  # Output: 2

7. sort(): Sorts the list in ascending order.

Code:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers)  # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

8. reverse(): Reverses the order of elements in the list.

Code:

fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits)  # Output: ["cherry", "banana", "apple"]

9. extend(): Appends the elements of another list to the end of the current list.

Code:

fruits = ["apple", "banana", "cherry"]
more_fruits = ["orange", "grape"]
fruits.extend(more_fruits)
print(fruits)  # Output: ["apple", "banana", "cherry", "orange", "grape"]

Example of Element Additions in a List

Code:

# Initialize a list
fruits = ["apple", "banana", "cherry"]

# Method 1: Using append() to add an element to the end of the list

fruits.append("orange")

# Method 2: Using insert() to add an element at a specified position

fruits.insert(1, "grape")

# Method 3: Using the + operator to concatenate lists and add multiple elements

fruits = fruits + ["kiwi", "mango"]

# Method 4: Using list comprehension to add elements based on some logic

fruits = [fruit + " juice" for fruit in fruits]

# Method 5: Using extend() to append elements from another list to the end

more_fruits = ["pineapple", "strawberry"]
fruits.extend(more_fruits)

# Method 6: Using slicing to insert elements at a specific position

fruits[2:2] = ["watermelon"]

# Print the final list of fruits
print(fruits)

This program demonstrates the use of various methods to add elements to the fruits list, including append(), insert(), + operator, list comprehension, extend(), and slicing.

Example of Deleting List Elements

Code:

# Initialize a list
fruits = ["apple", "banana", "cherry", "orange", "grape", "kiwi"]

# Method 1: Using pop() to remove and return an element by index

removed_fruit = fruits.pop(2)  # Remove the third element ("cherry")
print("Removed fruit:", removed_fruit)

# Method 2: Using remove() to remove the first occurrence of a specific element

fruits.remove("orange")

# Method 3: Using del statement to remove an element by index

del fruits[0]  # Remove the first element ("apple")

# Method 4: Using slicing to remove a range of elements

fruits[1:3] = []  # Remove the second and third elements ("banana" and "grape")

# Print the final list of fruits
print("Updated fruits list:", fruits)

The above code demonstrates four different methods for removing elements from a list in Python. Let us understand each method:

  • Method 1: Using pop() to remove and return an element by index:

fruits.pop(2) removes and returns the element at index 2 (which is "cherry") from the fruits list. The removed element is assigned to the variable removed_fruit. After this operation, the list fruits no longer contains "cherry."

  • Method 2: Using remove() to remove the first occurrence of a specific element:

fruits.remove("orange") removes the first occurrence of the element "orange" from the fruits list. This method removes elements based on their values, not their indices.

  • Method 3: Using del statement to remove an element by index:

del fruits[0] deletes the element at index 0 (which is "apple") from the fruits list. The del statement allows you to remove elements by specifying their indices.

  • Method 4: Using slicing to remove a range of elements:

fruits[1:3] = [] uses slicing to remove elements from index 1 to 2 (inclusive) in the fruits list. In this case, it removes "banana" (index 1) and "grape" (index 2). The empty list [] effectively removes the specified range of elements.

After applying these methods, the code prints the updated fruits list, which contains the elements that haven't been removed. In the final list, "cherry," "orange," "apple," "banana," and "grape" have been removed, leaving only "kiwi."

Advanced Example of List Methods in Python

Removing Duplicates from a List using a Function

Code:

def remove_duplicates(input_list):
    unique_list = []
    for item in input_list:
        if item not in unique_list:
            unique_list.append(item)
    return unique_list

my_list = [1, 2, 2, 3, 4, 4, 5]
result = remove_duplicates(my_list)
print(result)

Explanation:

This program defines a function remove_duplicates that takes a list as input. Inside the function, it initializes an empty list called unique_list to store unique elements. It iterates through each item in the input list and checks whether the item is already in the unique_list. If the item is not in the unique_list, it appends it, ensuring only unique elements are added. Finally, it returns the unique_list without duplicates.

List Comprehension for Matrix Transposition

Code:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed_matrix)

Explanation:

This program uses list comprehension to transpose a matrix represented as a list of lists.

The nested list comprehension iterates through the rows and columns of the original matrix, swapping rows and columns to create the transposed matrix.

Merging Sorted Lists

Code:

def merge_sorted_lists(list1, list2):
    merged_list = []
    i = j = 0

    while i < len(list1) and j < len(list2):
        if list1[i] < list2[j]:
            merged_list.append(list1[i])
            i += 1
        else:
            merged_list.append(list2[j])
            j += 1

    merged_list.extend(list1[i:])
    merged_list.extend(list2[j:])
    return merged_list

list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
result = merge_sorted_lists(list1, list2)
print(result)

Explanation:

This program defines a function merge_sorted_lists that takes two sorted lists as input and returns a merged and sorted list. It uses two pointers i and j to iterate through both lists while comparing elements. Elements from the two lists are compared, and the smaller one is added to the merged_list. After reaching the end of one of the lists, the remaining elements from the other list are appended to the merged_list. The result is a merged and sorted list.

Conclusion

Python's list methods are pivotal, bridging the gap between simple data storage and intricate data manipulations. Their flexibility and adaptability reinforce Python's reputation as a robust programming language. As we culminate our exploration of list methods in Python, it's evident that a thorough understanding of these tools can significantly elevate one's programming acumen. For those passionate about refining their skills and delving deeper into Python's treasures, upGrad offers a plethora of courses that resonate with today's industry demands.

FAQs

1. How do list methods in Python differ from tuple methods in Python?

While both deal with ordered collections, list methods emphasize mutability, whereas tuple methods are restricted due to the immutable nature of tuples.

2. Is there a distinction between list operations in Python and Python set methods?

Indeed, list operations cater to ordered collections, while set methods address unique, unordered collections.

3. How does the "extend" method offer advantages over using "+" for merging lists in Python?

The "extend" method modifies the original list, ensuring memory efficiency, whereas "+" creates an entirely new list, consuming more memory.

4. Could you draw a contrast between string methods in Python and the discussed list methods?

String methods are tailored for the string data type. Although there are overlapping operations, such as determining length, string methods can't manipulate data like lists due to strings' immutable nature.

5. Apart from "copy", are there other avenues to duplicate the contents of a Python list?

Certainly, techniques like slicing ([:]) or employing the list() constructor offer alternatives for list replication.

Pavan

PAVAN VADAPALLI

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...