List methods in Python

List methods in Python

In Python, a list is a built-in data type that can be used to store multiple items in a single variable. Lists are ordered, mutable, and allow duplicate values.

Below are the commonly used methods associated with lists:

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

    lst = [1, 2, 3] lst.append(4) # [1, 2, 3, 4] 
  2. extend(): Add elements from another list (or any iterable) to the current list.

    lst1 = [1, 2, 3] lst2 = [4, 5] lst1.extend(lst2) # [1, 2, 3, 4, 5] 
  3. insert(): Adds an element at a specified position.

    lst = [1, 2, 4] lst.insert(2, 3) # [1, 2, 3, 4] 
  4. remove(): Removes the specified element.

    lst = [1, 2, 3, 4] lst.remove(3) # [1, 2, 4] 
  5. pop(): Removes the element at a specified position (or the last item if the index is not specified).

    lst = [1, 2, 3, 4] lst.pop(1) # lst becomes [1, 3, 4] 
  6. clear(): Removes all elements from the list.

    lst = [1, 2, 3] lst.clear() # [] 
  7. index(): Returns the index of the first occurrence of the specified value.

    lst = [1, 2, 3, 4, 3] idx = lst.index(3) # 2 
  8. count(): Returns the number of occurrences of the specified value.

    lst = [1, 2, 3, 4, 3] count = lst.count(3) # 2 
  9. sort(): Sorts the list. You can specify ascending or descending order.

    lst = [3, 1, 4, 2] lst.sort() # [1, 2, 3, 4] 
  10. reverse(): Reverses the order of the list.

    lst = [1, 2, 3, 4] lst.reverse() # [4, 3, 2, 1] 
  11. copy(): Returns a shallow copy of the list.

    lst = [1, 2, 3] lst_copy = lst.copy() # [1, 2, 3] 

Note: The methods like sort(), reverse(), clear(), append(), extend(), insert(), remove(), and pop() modify the list in place and do not return a new list. If you need a new list while keeping the original list unchanged, consider using built-in functions like sorted() for sorting and using slicing for reversing.


More Tags

gridextra restore kotlin-null-safety amazon-cloudwatchlogs replace magento angular-ng-class lamp cryptographic-hash-function schedule

More Programming Guides

Other Guides

More Programming Examples