Python List Methods

The list in Python is a fundamental data structure that allows you to store ordered collections of items. Lists are mutable and can contain elements of different types. In this post, we will explore the complete list of Python list methods and see how they work in practical scenarios.

List Methods in Python
Python List Methods

1. The .append() Method

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

data = ["AviosIT", 2025, True]
data.append("Python")
print(data)
["AviosIT", 2025, True, "Python"]

2. The .extend() Method

The .extend() method adds all elements of an iterable to the end of the list.

data = ["AviosIT", 2025, True]
data.extend(["Programming", "Code"])
print(data)
["AviosIT", 2025, True, "Programming", "Code"]

3. The .insert() Method

The .insert() method inserts an element at a specified index.

data = ["AviosIT", 2025, True]
data.insert(1, "Tech")
print(data)
["AviosIT", "Tech", 2025, True]

4. The .remove() Method

The .remove() method removes the first occurrence of a specified value.

data = ["AviosIT", 2025, True]
data.remove(True)
print(data)
["AviosIT", 2025]

5. The .pop() Method

The .pop() method removes and returns the element at the specified index or the last element if no index is provided.

data = ["AviosIT", 2025, True]
removed_item = data.pop(1)
print(data)
["AviosIT", True]

6. The .clear() Method

The .clear() method removes all elements from the list.

data = ["AviosIT", 2025, True]
data.clear()
print(data)
[]

7. The .index() Method

The .index() method returns the index of the first occurrence of a specified value.

data = ["AviosIT", 2025, True]
print(data.index(2025))
1

8. The .count() Method

The .count() method returns the number of occurrences of a specified value.

data = ["AviosIT", 2025, True, "AviosIT"]
print(data.count("AviosIT"))
2

9. The .sort() Method

The .sort() method sorts the list in ascending order by default. Note: Sorting works only if elements are of the same type.

data = [2025, 3, 42, 1]
data.sort()
print(data)
[1, 3, 42, 2025]

10. The .reverse() Method

The .reverse() method reverses the elements of the list.

data = ["AviosIT", 2025, True]
data.reverse()
print(data)
[True, 2025, "AviosIT"]

11. The .copy() Method

The .copy() method creates a shallow copy of the list.

data = ["AviosIT", 2025, True]
copy_data = data.copy()
print(copy_data)
["AviosIT", 2025, True]

12. The .len() Function

Although not a method, the len() function is used to determine the number of items in a list.

data = ["AviosIT", 2025, True]
print(len(data))
3

Conclusion

In this post, we've explored all the list methods available in Python using the sample data ["AviosIT", 2025, True]. These methods provide essential tools for managing and manipulating lists, enabling you to handle data efficiently in various applications. Mastering these methods will significantly enhance your Python programming skills. Happy coding!

advertise
advertise
advertise
advertise