Hashtag Technophile

10 Common Python List Methods that every Developer should know.

Hello Technophiles! In this article, let’s look into the most common list methods that are used in Python programming language which enables you to manipulate and work with lists effectively in Python.

Let’s jump into the list methods one by one along with a sample code for each method which can give you a clear understanding.

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

# Creating a list
my_list = [1, 2, 3]

# Append and Extend
my_list.append(4)

print(my_list)  # Output: [1, 2, 3, 4]

2. extend(iterable): Appends all elements from the iterable (e.g., another list or any iterable) to the end of the list.

# Creating a list
my_list = [1, 2, 3, 4]

my_list.extend([5, 6, 7])

print(my_list)  # Output: [1, 2, 3, 4, 5, 6, 7]

3. insert(i, x): Inserts element x at position i in the list.

# Creating a list
my_list = [1, 2, 3, 4, 5]

# Insert
my_list.insert(2, 100)

print(my_list)  # Output: [1, 2, 100, 3, 4, 5]

4. remove(x): Removes the first occurrence of element x from the list.

# Creating a list
my_list = [1, 2, 100, 3, 4, 5, 6, 7]

# Remove
my_list.remove(100)

print(my_list)  # Output: [1, 2, 3, 4, 5, 6, 7]

5. pop([i]): Removes and returns the element at index i. If i is not provided, it removes and returns the last element.

# Creating a list
my_list = [1, 2, 3, 4, 5, 6, 7]

# Pop
popped_element = my_list.pop(2)

print(popped_element)  # Output: 3

print(my_list)         # Output: [1, 2, 4, 5, 6, 7]

6. index(x[, start[, end]]): Returns the index of the first occurrence of element x in the list within the given optional range [start:end]. Raises a ValueError if x is not found.

# Creating a list
my_list = [1, 2, 4, 5, 6, 7]

# Index
print(my_list.index(5))    # Output: 3

7. count(x): Returns the number of occurrences of element x in the list.

# Creating a list
my_list = [1, 2, 4, 5, 6, 7]

# Count
print(my_list.count(5))    # Output: 1

8. sort(key=None, reverse=False): Sorts the list in ascending order by default. The key parameter allows specifying a custom function for sorting. If reverse=True, the list is sorted in descending order.

# Creating a list
my_list = [1, 2, 5, 4, 7, 6]

# Sort
my_list.sort()

print(my_list)  # Output: [1, 2, 4, 5, 6, 7]

9. reverse(): Reverses the elements of the list in place.

# Creating a list
my_list = [1, 2, 5, 4, 7, 6]

# Reverse
my_list.reverse()

print(my_list)  # Output: [7, 6, 5, 4, 2, 1]

10. clear(): Removes all elements from the list.

# Creating a list
my_list = [1, 2, 5, 4, 7, 6]

# Clear
my_list.clear()

print(my_list)  # Output: []

If you have read this far, I hope you are finding it useful.

Make sure you rate or comment this article and do share & subscribe our website because that encourages our team to write more

Cheers! Until next time…❤

5 1 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top