DEV Community

Anirban Das
Anirban Das

Posted on

Python Array List Methods

Python has a set of built-in methods that you can use on lists/arrays.

1) append(elmnt)

Adds an element at the end of the list

fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
Enter fullscreen mode Exit fullscreen mode

2) clear()

Removes all the elements from the list

fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
print(fruits) # []
Enter fullscreen mode Exit fullscreen mode

3) copy()

Returns a copy of the list

fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x) # ['apple', 'banana', 'cherry']
Enter fullscreen mode Exit fullscreen mode

4) count(value)

Returns the number of elements with the specified value

arr = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = arr.count(9)
print(x) # 2
Enter fullscreen mode Exit fullscreen mode

5) extend(iterable)

Add the elements of a list (or any iterable), to the end of the current list

fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits) # ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
Enter fullscreen mode Exit fullscreen mode

6) index(elmnt)

Returns the index of the first element with the specified value

numbers = [4, 55, 64, 32, 16, 32]
x = numbers.index(32)
print(x) # 3
Enter fullscreen mode Exit fullscreen mode

7) insert(pos, elmnt)

Adds an element at the specified position

fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits) # ['apple', 'orange', 'banana', 'cherry']
Enter fullscreen mode Exit fullscreen mode

8) pop(pos)

Removes the element at the specified position

fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits) # ['apple', 'cherry']
Enter fullscreen mode Exit fullscreen mode

9) remove(elmnt)

Removes the first item with the specified value

fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits) # ['apple', 'cherry']
Enter fullscreen mode Exit fullscreen mode

10) reverse()

Reverses the order of the list

fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits) # ['cherry', 'banana', 'apple']
Enter fullscreen mode Exit fullscreen mode

11) sort(reverse=True|False, key=myFunc)

The sort() method sorts the list ascending by default.

cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars) # ['BMW', 'Ford', 'Volvo']
Enter fullscreen mode Exit fullscreen mode

References:

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs