Open In App

Concept of Mutable Lists in Python

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we can use mutable lists which are lists that we can change after creating them. We can add, remove, or modify items in the list without creating a new one. In this article, we will check the concept of Mutable lists in Python.

Here are some examples that illustrate the concept of mutable lists in Python:

Modifying Elements of a List

We can modify an element in a list by accessing it through its index and assigning a new value.

Python
a = [1, 2, 3, 4, 5]

# Modifying an element
a[2] = 10
print(a)

Output
[1, 2, 10, 4, 5]

Adding Elements in a list

We can add a single element to the end of a list using the append() method.

Python
a = [1, 2, 3, 4, 5]

# Appending 6 to the end of the list
a.append(6)  
print(a)

Output
[1, 2, 3, 4, 5, 6]

Removing Elements in a List

We can remove the first occurrence of a specific element from a list using the remove() method.

Python
a = [1, 2, 3, 4, 5]

# Removing element with value 3 from the list
a.remove(3)
print(a)

Output
[1, 2, 4, 5]

Extending list with another list

We can add all elements from another list to the end of our list using the extend() method.

Python
a= [1, 2, 3]

# Add elements of another list
a.extend([4, 5, 6])  
print(a)

Output
[1, 2, 3, 4, 5, 6]

Slicing and Modifying a Sublist

We can slice a list to create a sublist and modify elements within that sublist.

Python
a = [1, 2, 3, 4, 5]

# Slicing and modifying a sublist
a[1:4] = [20, 30, 40]
print(a)

Output
[1, 20, 30, 40, 5]

Various Methods used in Lists

Let's understand the various methods of the mutable lists.

Method

Method's description

append()

Add a single element to the end of the list

pop()

Removes and returns the element at index i (default is the last item).

clear()

Removes all elements from the list, leaving it empty.

reduce()

Repeatedly applies a function to an iterable, reducing it to a single value.

sum()

Returns the sum of all elements in an iterable.

ord()

Returns the character’s numeric code point.

max()

Returns the largest element from the list.

min()

Returns the smallest element from the list.

extend()

Appends all elements from the another list to the end of the list.

remove()

Removes the first occurrence of element from the list.

insert()

Inserts element at the specified index in the list.

reverse()

Reverses the elements of the list in place.

sort(key=None,reverse=False)

Sorts the list in ascending order, optionally using a custom sort key or in reverse order.

index()

Returns the index of the first occurrence of element within the optional start and end range.

count()

Returns the number of times element appears in the list.

all()

Returns True if all elements are true or the list is empty.

copy()

Returns shallow copy of the list.

del list[i]

Deletes the element at index i from the list.


Next Article

Similar Reads