Python List Methods and its Basic Analyses

List Methods[1] and its Basic Analyses[2]

append(): O(1)

extend(): O(k)

insert(): O(n)

remove(): O(n)

index(): O(n)

count(): O(n)

pop(): O(1)

reverse(): O(n)

sort(): O(n log n)

copy(): O(n)

clear(): O(n)


append(): The append() method adds an item to the end of the list.

Input:

  • item - takes a single item and adds it to the end of the list. The item can be numbers, strings, another list, dictionary etc.

Output:

  • This method doesn’t return any value

extend(): The extend() extends the list by adding all items of a list (passed as an argument) to the end.

insert(): The insert() method inserts the element to the list at the given index.

Input:

  • index - position where element needs to be inserted.
  • element - this is the element to be inserted in the list.

Output:

  • This method doesn’t return any value

remove()

index()

count(): The count() method returns the number of occurrences of an element in a list.

pop()

reverse()

sort(): The sort() method sorts the elements of a given list.

Input:

  • By default, this method doesn’t require any extra parameters.
  • However, it has two optional parameters:
    • reverse - If true, the sorted list is reversed (or sorted in Descending order)
    • key - function that serves as a key for the sort comparison

Examples:

  • How to sort in descending order?

    list.sort(reverse=True)

  • How to sort using your own function with key parameter?

    list.sort(key = func)

    note: func can be a lambda function too

Example:

list.sort(reverse=True)

clear():