Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python List: Functions and Methods

Python List Functions - Complete Guide

Learn how to use Python list methods including append, insert, remove, pop, sort, and reverse.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to List Functions
  • append() — Add to End
  • insert() — Add at Position
  • extend() — Merge Lists
  • remove() — Delete by Value
  • pop() — Remove by Index
  • sort() — Sort Elements
  • reverse() — Reverse Order
  • Other Useful Methods
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • append() — add elements to the end of a list
  • insert() — add elements at a specific position
  • extend() — merge two lists
  • remove() — delete elements by value
  • pop() — remove elements by index
  • sort() — sort list elements
  • reverse() — reverse list order
  • Other methods — index, count, copy, clear

Introduction to List Functions

Python lists provide a rich set of built-in methods for manipulating list data. These methods allow you to add, remove, modify, and organize elements efficiently. Understanding these methods is essential for effective list manipulation in Python.

List methods can be categorized into several groups:

  • Adding methods: append(), insert(), extend()
  • Removing methods: remove(), pop(), clear()
  • Ordering methods: sort(), reverse()
  • Searching methods: index(), count()
  • Utility methods: copy(), len()

Most list methods modify the list in place (mutating the original list) rather than creating a new list. This behavior is important to understand when working with list operations.

💡 Key concept: Most list methods modify the original list directly and return None. This is different from functions like sorted() which return a new list.

append() — Add to End

1

Adding Elements to the End

The append() method adds a single element to the end of a list. This is one of the most frequently used list methods.

# Basic usage
fruits = ["apple", "banana", "cherry"]
print(fruits)  # ['apple', 'banana', 'cherry']

fruits.append("mango")
print(fruits)  # ['apple', 'banana', 'cherry', 'mango']

# Appending different data types
numbers = [1, 2, 3]
numbers.append(4)           # Integer
numbers.append("five")      # String
numbers.append([6, 7])      # List
print(numbers)  # [1, 2, 3, 4, 'five', [6, 7]]

# Appending in a loop
squares = []
for i in range(5):
    squares.append(i ** 2)
print(squares)  # [0, 1, 4, 9, 16]

Characteristics:

  • Adds a single element to the end of the list
  • Modifies the list in place (returns None)
  • Can add any data type (integer, string, list, etc.)
  • Time complexity: O(1) — constant time
  • Most common way to build lists dynamically

Quick Check: What does append() return? (Answer: None — it modifies the list in place)

insert() — Add at Position

2

Inserting at a Specific Position

The insert() method adds an element at a specified index position. Existing elements shift to the right to make room.

# Basic usage
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "mango")  # Insert at index 1
print(fruits)  # ['apple', 'mango', 'banana', 'cherry']

# Insert at the beginning (index 0)
fruits.insert(0, "orange")
print(fruits)  # ['orange', 'apple', 'mango', 'banana', 'cherry']

# Insert at the end (using len())
fruits.insert(len(fruits), "grape")
print(fruits)  # ['orange', 'apple', 'mango', 'banana', 'cherry', 'grape']

# Insert with negative index (from the end)
fruits.insert(-1, "kiwi")  # Insert before the last element
print(fruits)  # ['orange', 'apple', 'mango', 'banana', 'cherry', 'kiwi', 'grape']

Characteristics:

  • Accepts two arguments: index and element
  • Modifies the list in place
  • Supports negative indexing (counts from the end)
  • If index is out of range, inserts at the end
  • Time complexity: O(n) — linear time (shifts elements)

Quick Check: What happens when you insert at index 0? (Answer: The element is added at the beginning)

extend() — Merge Lists

3

Merging Two Lists

The extend() method adds all elements from one iterable to the end of another list. It effectively merges two lists.

# Basic usage
fruits1 = ["apple", "banana"]
fruits2 = ["cherry", "mango", "orange"]

fruits1.extend(fruits2)
print(fruits1)  # ['apple', 'banana', 'cherry', 'mango', 'orange']

# Extending with a tuple
numbers = [1, 2, 3]
numbers.extend((4, 5, 6))
print(numbers)  # [1, 2, 3, 4, 5, 6]

# Extending with a string (adds each character)
letters = ['a', 'b']
letters.extend('cd')
print(letters)  # ['a', 'b', 'c', 'd']

# Compare with append (notice the difference)
list1 = [1, 2]
list2 = [3, 4]
list1.append(list2)   # Adds the entire list as one element
print(list1)  # [1, 2, [3, 4]]

list1 = [1, 2]
list1.extend(list2)   # Adds each element individually
print(list1)  # [1, 2, 3, 4]

Characteristics:

  • Accepts any iterable (list, tuple, string, set)
  • Adds each element individually
  • Modifies the list in place
  • Different from append() which adds as a single element
  • Time complexity: O(k) where k is the length of the iterable

Quick Check: What is the difference between extend() and append()? (Answer: extend() adds each element individually; append() adds the entire object as one element)

remove() — Delete by Value

4

Removing the First Occurrence

The remove() method removes the first occurrence of a specified value from the list.

# Basic usage
fruits = ["apple", "banana", "cherry", "banana", "mango"]
fruits.remove("banana")  # Removes the first 'banana'
print(fruits)  # ['apple', 'cherry', 'banana', 'mango']

# Trying to remove a value that doesn't exist (ValueError)
# fruits.remove("grape")  # Raises ValueError

# Removing with condition using a loop
numbers = [1, 2, 3, 4, 5]
for num in numbers[:]:  # Iterate over a copy
    if num % 2 == 0:
        numbers.remove(num)
print(numbers)  # [1, 3, 5]

Characteristics:

  • Removes the first occurrence of the value
  • Raises ValueError if the value is not found
  • Modifies the list in place
  • Time complexity: O(n) — searches the list
  • Check existence with in before removing to avoid errors

Quick Check: What happens if you try to remove a value that doesn't exist? (Answer: ValueError is raised)

pop() — Remove by Index

5

Removing and Returning Elements

The pop() method removes and returns an element at a specified index. Without an argument, it removes the last element.

# Basic usage
fruits = ["apple", "banana", "cherry", "mango", "orange"]

# Remove the last element (default)
last = fruits.pop()
print(last)     # orange
print(fruits)   # ['apple', 'banana', 'cherry', 'mango']

# Remove at a specific index
item = fruits.pop(1)  # Remove at index 1
print(item)     # banana
print(fruits)   # ['apple', 'cherry', 'mango']

# Pop with negative indexing
item = fruits.pop(-1)  # Remove the last element
print(item)     # mango
print(fruits)   # ['apple', 'cherry']

# Stack behavior (LIFO - Last In, First Out)
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop())  # 3
print(stack.pop())  # 2
print(stack)        # [1]

Characteristics:

  • Removes and returns the element
  • Without index: removes the last element (pop from end)
  • With index: removes at that position
  • Raises IndexError if index is out of range
  • Time complexity: O(1) for last element, O(n) for arbitrary index
  • Useful for implementing stack (LIFO) behavior

Quick Check: What does pop() return? (Answer: The removed element)

sort() — Sort Elements

6

Sorting List Elements

The sort() method sorts the elements of a list in ascending order by default. It modifies the list in place.

# Basic sorting (ascending)
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 9]

# Sorting strings (alphabetical)
fruits = ["mango", "apple", "banana", "cherry"]
fruits.sort()
print(fruits)  # ['apple', 'banana', 'cherry', 'mango']

# Descending order
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort(reverse=True)
print(numbers)  # [9, 5, 4, 3, 2, 1, 1]

# Sorting with a key function
words = ["apple", "banana", "cherry", "date"]
words.sort(key=len)  # Sort by length
print(words)  # ['date', 'apple', 'banana', 'cherry']

# Sorting with a custom key (case-insensitive)
names = ["Alice", "bob", "Charlie", "dave"]
names.sort(key=str.lower)
print(names)  # ['Alice', 'bob', 'Charlie', 'dave']

Characteristics:

  • Modifies the list in place
  • Default sorting is ascending
  • Use reverse=True for descending order
  • Supports key parameter for custom sorting logic
  • Time complexity: O(n log n)
  • Cannot sort lists with mixed data types

Quick Check: What does sort() return? (Answer: None — it sorts the list in place)

reverse() — Reverse Order

7

Reversing the List Order

The reverse() method reverses the order of elements in the list. It modifies the list in place.

# Basic usage
fruits = ["apple", "banana", "cherry", "mango"]
fruits.reverse()
print(fruits)  # ['mango', 'cherry', 'banana', 'apple']

# Reverse with numbers
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers)  # [5, 4, 3, 2, 1]

# Compare with slicing (creates a copy)
original = [1, 2, 3, 4, 5]
reversed_copy = original[::-1]  # Creates a new list
original.reverse()              # Modifies in place

print(original)       # [5, 4, 3, 2, 1]
print(reversed_copy)  # [5, 4, 3, 2, 1]

Characteristics:

  • Modifies the list in place
  • Time complexity: O(n)
  • For a non-mutating reverse, use slicing: list[::-1]
  • Different from reversed() which returns an iterator

Quick Check: What is the difference between reverse() and [::-1]? (Answer: reverse() modifies in place; [::-1] creates a new list)

Other Useful Methods

8

Additional List Methods

# index() - Find the position of an element
fruits = ["apple", "banana", "cherry", "banana", "mango"]
print(fruits.index("cherry"))  # 2
print(fruits.index("banana"))  # 1 (first occurrence)

# count() - Count occurrences
print(fruits.count("banana"))  # 2
print(fruits.count("grape"))   # 0

# copy() - Create a shallow copy
original = [1, 2, 3]
copied = original.copy()
copied.append(4)
print(original)  # [1, 2, 3] (unchanged)
print(copied)    # [1, 2, 3, 4]

# clear() - Remove all elements
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)  # []

# len() - Get the length (built-in function)
fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # 3

# max() and min() - Get max/min values
numbers = [3, 1, 4, 1, 5, 9, 2]
print(max(numbers))  # 9
print(min(numbers))  # 1

# sum() - Sum all elements
numbers = [1, 2, 3, 4, 5]
print(sum(numbers))  # 15

# all() and any() - Check conditions
numbers = [1, 2, 3, 4, 5]
print(all(x > 0 for x in numbers))  # True
print(any(x > 4 for x in numbers))  # True

Method summaries:

  • index(x) — returns the index of the first occurrence of x
  • count(x) — returns the number of occurrences of x
  • copy() — creates a shallow copy of the list
  • clear() — removes all elements from the list
  • len() — returns the number of elements (built-in)
  • max()/min() — returns the largest/smallest element
  • sum() — returns the sum of all elements (numeric)

Common Mistakes

9

Pitfalls and Solutions

Confusing append() with extend()

This is one of the most common mistakes when working with lists.

# Incorrect expectation
list1 = [1, 2]
list2 = [3, 4]
list1.append(list2)  # Adds list2 as a single element
print(list1)  # [1, 2, [3, 4]]  ← Not [1, 2, 3, 4]

# Correct for adding individual elements
list1 = [1, 2]
list1.extend(list2)  # Adds each element individually
print(list1)  # [1, 2, 3, 4]  ✓

Forgetting that sort() and reverse() return None

# Incorrect — trying to assign the result
numbers = [3, 1, 4, 1, 5]
sorted_numbers = numbers.sort()  # Returns None!
print(sorted_numbers)  # None

# Correct — sort modifies in place
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)  # [1, 1, 3, 4, 5]

Removing from a list while iterating

# Incorrect — modifies list during iteration
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # Skips elements

# Correct — iterate over a copy
numbers = [1, 2, 3, 4, 5]
for num in numbers[:]:
    if num % 2 == 0:
        numbers.remove(num)
print(numbers)  # [1, 3, 5]

Using pop() with an out-of-range index

# Incorrect — raises IndexError
fruits = ["apple", "banana"]
# fruits.pop(5)  # IndexError: pop index out of range

# Correct — check length first
if len(fruits) > 5:
    fruits.pop(5)

Quick Check: What is the most common mistake with append()? (Answer: Confusing it with extend() — append() adds the entire object as one element)

Interactive Editor

Experiment with list methods in the interactive editor below. Modify the code and observe the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
LIST METHODS PRACTICE
========================================

Original: ['apple', 'banana', 'cherry']

1. APPEND()
After append: ['apple', 'banana', 'cherry', 'mango']

2. INSERT()
After insert: ['apple', 'orange', 'banana', 'cherry', 'mango']

3. EXTEND()
After extend: ['apple', 'orange', 'banana', 'cherry', 'mango', 'grape', 'kiwi']

4. REMOVE()
After remove: ['apple', 'orange', 'cherry', 'mango', 'grape', 'kiwi']

5. POP()
Popped: kiwi
After pop: ['apple', 'orange', 'cherry', 'mango', 'grape']

6. SORT()
After sort: ['apple', 'cherry', 'grape', 'mango', 'orange']

7. REVERSE()
After reverse: ['orange', 'mango', 'grape', 'cherry', 'apple']

8. INDEX() AND COUNT()
Index of 'cherry': 3
Count of 'apple': 1

List methods practice complete!
🏆

Certificate of Completion

You have completed the Python List Functions tutorial. You now understand append, insert, extend, remove, pop, sort, reverse, and other essential list methods.

Quiz

Test your understanding of list methods:

1. Which method adds a single element to the end of a list?
2. What is the difference between append() and extend()?
3. Which method removes and returns the last element of a list?
4. What does the sort() method return?
5. Which method removes all elements from a list?

Frequently Asked Questions

What is the difference between append() and extend()? ▼

append() adds the entire object as a single element at the end of the list. extend() iterates over the argument and adds each element individually. Use append() for single elements and extend() for merging lists.

Why do sort() and reverse() return None? ▼

These methods modify the list in place for performance reasons. Returning None indicates that the list has been modified directly. If you need a new list, use sorted() or slicing list[::-1].

What happens if I try to remove a value that doesn't exist? ▼

remove() raises a ValueError if the value is not found. Always check for existence using if value in list: before removing to avoid errors.

How do I create a copy of a list? ▼

Use the copy() method or slicing list[:]. Both create a shallow copy. For nested lists, use copy.deepcopy() from the copy module.

What is the time complexity of list operations? ▼

append() and pop() (without index) are O(1). insert(), remove(), and pop(index) are O(n) because they shift elements. sort() is O(n log n).

How do I sort a list in descending order? ▼

Use sort(reverse=True) for in-place sorting, or sorted(list, reverse=True) to create a new sorted list. For reverse order of an already sorted list, use reverse().

Next Steps

After mastering list functions, consider exploring these related topics:

List Iteration

Loop through lists using for loops, while loops, and enumerate().

Learn More →

List Comprehension

Concise way to create and transform lists in one line.

Learn More →

Python Tuples

Immutable sequences and their methods.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • Python Data Types Interview Questions
Previous: List Iteration Next: List Comprehension →