Python From Beginner to Advanced

0% completed

Previous
Next
Python - List Methods

Lists in Python are equipped with a variety of methods designed to facilitate the manipulation of their contents. These methods provide functionalities for adding items, removing items, sorting, and more, making lists highly versatile for managing collections of data in Python programs.

List Methods

Here’s a table summarizing common list methods along with rephrased descriptions:

MethodDescriptionTime Complexity
append(obj)Adds an item obj to the end of the list.O(1)
clear()Empties the list, removing all its items.O(1)
copy()Creates a duplicate of the list.O(n)
count(obj)Tallies the occurrence of obj within the list.O(n)
extend(seq)Merges another iterable seq into the list.O(k)
index(obj)Finds the first appearance of obj and returns its position.O(n)
insert(index, obj)Inserts obj at the specified index.O(n)
pop(obj=list[-1])Extracts and returns the item at obj index, defaults to the last item.O(1) for last item, O(n) for other positions
remove(obj)Deletes the first occurrence of obj from the list.O(n)
reverse()Inverts the order of items in the list.O(n)
sort([func])Organizes the list items. If func is provided, it uses this function for sorting.O(n \log n)

Example 1: Using append()

The append() method is used to add an item to the end of a list. This is particularly useful when building up a list dynamically.

Python3
Python3

. . . .

Explanation:

  • my_pets = ['dog', 'cat']: Initializes the list with two elements: 'dog' and 'cat'.
  • my_pets.append('rabbit'): Adds 'rabbit' to the end of the my_pets list.
  • The print statement outputs the updated list with the newly appended item.

Example 2: Using remove()

The remove() method deletes the first occurrence of a specified item from the list. It is useful for removing unwanted elements.

Python3
Python3

. . . .

Explanation:

  • my_colors = ['red', 'blue', 'green', 'blue']: Starts with a list that includes 'blue' twice.
  • my_colors.remove('blue'): Removes the first 'blue' from the list.
  • The final print statement shows the list after the first 'blue' has been removed, demonstrating that only the first instance was deleted.

These examples highlight how list methods can be utilized to manage and manipulate list data effectively. By using these built-in methods, Python developers can perform a wide range of list operations efficiently and intuitively.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next