lists

  1. len(): Returns the number of elements in a list.
    • numbers = [1, 2, 3, 4, 5]
    • length = len(numbers)
    • print(length) # Output: 5
  2. append(): Adds an element to the end of a list.
    • fruits = ["apple", "banana"]
    • fruits.append("cherry")
    • print(fruits) # Output: ["apple", "banana", "cherry"]
  3. insert(): Inserts an element at a specific index in the list.
    • fruits = ["apple", "banana", "cherry"]
    • fruits.insert(1, "grape")
    • print(fruits) # Output: ["apple", "grape", "banana", "cherry"]
  4. remove(): Removes the first occurrence of a specified element from the list.
    • fruits = ["apple", "banana", "cherry"]
    • fruits.remove("banana")
    • print(fruits) # Output: ["apple", "cherry"]
  5. pop(): Removes and returns the last element of the list or an element at a specific index.
    • fruits = ["apple", "banana", "cherry"]
    • popped = fruits.pop()
    • print(popped) # Output: "cherry"
  6. index(): Returns the index of the first occurrence of a specified element in the list.
    • fruits = ["apple", "banana", "cherry"]
    • index = fruits.index("banana")
    • print(index) # Output: 1
  7. count(): Returns the number of occurrences of a specified element in the list.
    • fruits = ["apple", "banana", "cherry", "banana"]
    • count = fruits.count("banana")
    • print(count) # Output: 2
  8. sort(): Sorts the list in ascending order (in-place modification).
    • numbers = [3, 1, 4, 2, 5]
    • numbers.sort()
    • print(numbers) # Output: [1, 2, 3, 4, 5]
  9. reverse(): Reverses the order of elements in the list (in-place modification).
    • numbers = [1, 2, 3, 4, 5]
    • numbers.reverse()
    • print(numbers) # Output: [5, 4, 3, 2, 1]

These are just a few examples of the functions and methods available for manipulating lists in Python. Python provides many more built-in functions and additional methods to work with lists effectively.

Leave a comment