Common List Methods

Introduction

In Python, Lists are mutable, ordered collections of elements. Python list presents a range of methods that make it easy to operate and manipulate these lists. In this portion, we will discuss the common list methods in Python with examples for each.

Caution

Remember, List operations can change the list!

Append

append() method in Python adds a single element to the end of the list.

1fruits = ["apple", "banana", "cherry"]
2fruits.append("orange")
3print(fruits)

The above code will output: ['apple', 'banana', 'cherry', 'orange']

Extend

extend() method in Python appends iterable elements such as a list, tuple, string etc to the end of the list.

1fruits = ["apple", "banana", "cherry"]
2fruits.extend(["orange", "mango"])
3print(fruits)

The above code will output: ['apple', 'banana', 'cherry', 'orange', 'mango']

Insert

insert() method in Python can add an element to the list at a specific position.

1fruits = ["apple", "banana", "cherry"]
2fruits.insert(1, "orange")
3print(fruits)

The above code will output: ['apple', 'orange', 'banana', 'cherry']

Remove

remove() method in Python removes the first occurrence of the element in the list.

1fruits = ["apple", "banana", "cherry", "banana"]
2fruits.remove("banana")
3print(fruits)

The above code will output: ['apple', 'cherry', 'banana']

Pop

pop() method in Python removes and returns the element at the given index from the list.

1fruits = ["apple", "banana", "cherry"]
2removed = fruits.pop(1)
3print(fruits)
4print(removed)

The above code will output ['apple', 'cherry'] as the list after removing and print banana as the removed element.

Conclusion

These are some of the most commonly used list methods in Python that allow efficient manipulation of lists. Understanding and using them can improve both your effectiveness and your code’s readability.