Menu
Coddy logo textTech

List Methods

Part of the Fundamentals section of Coddy's Python journey — lesson 56 of 77.

Lists are packed with many methods (functionalities). To access a method, write:

some_list.method()

Here is a list of the basic methods:

  • append(element) - adds a single element to the end of the list
  • clear() - removes all elements from the list
  • pop(index) - removes an element at the specified index
  • reverse() - reverses the order of the list
  • sort() - sorts the list in ascending order

Important Note: The append() method adds a single element. If you try to append an entire list, it will be added as a nested list, which is usually not what you want. For example:

lst1 = [1, 2]
lst2 = [3, 4]
lst1.append(lst2)  # Wrong approach for merging
print(lst1)  # Output: [1, 2, [3, 4]] - lst2 is nested inside!

To combine elements from two lists, use a loop to append individual elements instead.

Here is an example of how to use the append method correctly:

my_list = ["orange", "banana", "apple"]
my_list.append("strawberry")
print(my_list)

This will output ["orange", "banana", "apple", "strawberry"].

Example of the clear method:

my_list = [1, 2, 3, 4, 5]
my_list.clear()
print(my_list)

This will output [].

Example of the sort method:

my_list = [1, 9, 2, 3]
my_list.sort()
print(my_list)

This will output [1, 2, 3, 9].

challenge icon

Challenge

Easy

Write a function named merge that receives two lists as arguments and merges them into one sorted list.

What is provided: The function signature is already written for you:

def merge(lst1, lst2):
    # Write code here

What you need to do: Fill in the body of the function to:

  1. Combine all elements from both lists into a single list
  2. Sort the combined list in ascending order
  3. Return the sorted list

Example: merge([1, 4, 2], [2, 5, 9]) should return [1, 2, 2, 4, 5, 9]

Cheat sheet

Basic list methods in Python:

  • append(element): Adds an element to the end of the list
  • clear(): Removes all elements from the list
  • pop(index): Removes and returns an element at the specified index
  • reverse(): Reverses the order of the list
  • sort(): Sorts the list in ascending order

Example usage:

my_list = [1, 9, 2, 3]
my_list.append(5)  # [1, 9, 2, 3, 5]
my_list.sort()     # [1, 2, 3, 5, 9]
my_list.clear()    # []

Try it yourself

def merge(lst1, lst2):
    # Write code here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals