Open In App

Concept of Mutable Lists in Python

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The concept of mutable lists refers to lists whose elements can be modified or changed after the list is created. In programming, a list is a data structure that stores an ordered collection of elements. The mutability of a list determines whether you can modify its contents, such as adding or removing elements, changing the values of existing elements, or reordering the elements. In this article, we will see the concept of mutable lists in Python.

Mutable and Immutable DataTypes in Python

Below are the examples by which we can understand more about mutable and immutable data types in Python:

Mutable Data Type

Mutable data types are those data types whose values can be changed once created. In Python, lists, and dictionaries are mutable data types. One can change the value of the list once assigned.

In this example, we have changed the value of the element at index 4, i.e., “e” with “hello”. This reflects that lists in Python are mutable.

Python




list=['a','b','c','d','e','f','g','h']
print("original list ")
print(list)
  
 # changing element at index 4 ,i.e., e to hello
list[4]='hello' 
print("changed list")
print(list)


Output

original list 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
changed list
['a', 'b', 'c', 'd', 'hello', 'f', 'g', 'h']




Immutable DataType

Immutable data types are those data types whose values cannot be changed once created . In Python, string, tuple etc, are immutable data type. One cannot change the value of list once assign.

Python




str= "hello"
print("original  string")
print(str)
  
str[2]="p" #gives an error


Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
str[2]="p" #gives an error
TypeError: 'str' object does not support item assignment

Concept Of Mutable Lists

A mutable list is a type of list where you can modify its elements, such as adding or removing items, changing the value of existing items, or reordering the elements. Mutable lists are often used when you need to frequently update, insert, or remove elements from the list, as it allows for more efficient manipulation of the data structure.

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

Modifying Elements in a List in Python

In this example, the original list `my_list` is created with elements [1, 2, 3, 4, 5]. The code then modifies the element at index 2 by assigning the value 10, resulting in the updated list [1, 2, 10, 4, 5].

Python




# Original list
my_list = [1, 2, 3, 4, 5]
  
# Modifying an element
my_list[2] = 10
  
print(my_list)  # Output: [1, 2, 10, 4, 5]


Output

[1, 2, 10, 4, 5]




Adding Elements in a Python Mutable List

In this example, the original list `my_list` is initialized with elements [1, 2, 3, 4, 5]. The code appends the value 6 to the end of the list, resulting in the modified list [1, 2, 3, 4, 5, 6].

Python




# Original list
my_list = [1, 2, 3, 4, 5]
  
# Adding a new element
my_list.append(6)
  
print(my_list)  # Output: [1, 2, 3, 4, 5, 6]


Output

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




Removing Elements in a List in Python

In this example, the original list `my_list` is initialized with elements [1, 2, 3, 4, 5]. The code removes the element with the value 3 from the list, resulting in the updated list [1, 2, 4, 5].

Python




# Original list
my_list = [1, 2, 3, 4, 5]
  
# Removing an element
my_list.remove(3)
  
print(my_list)  # Output: [1, 2, 4, 5]


Output

[1, 2, 4, 5]




Slicing and Modifying a Sublist in a Python List

In this example, the original list `my_list` is initialized with elements [1, 2, 3, 4, 5]. The code uses slicing to target the sublist from index 1 to 4 (excluding 4) and replaces it with the values [20, 30, 40], resulting in the modified list [1, 20, 30, 40, 5].

Python




# Original list
my_list = [1, 2, 3, 4, 5]
  
# Slicing and modifying a sublist
my_list[1:4] = [20, 30, 40]
  
print(my_list)  # Output: [1, 20, 30, 40, 5]


Output

[1, 20, 30, 40, 5]




Clearing the Entire List in Python

In this example, the original list `my_list` is initialized with elements [1, 2, 3, 4, 5]. The code uses the `del` statement with slicing to clear the entire list, resulting in an empty list, `my_list = []`.

Python3




# Original list
my_list = [1, 2, 3, 4, 5]
  
# Clearing the entire list
del my_list[:]
  
print(my_list)  # Output: []


Output

[]




Conclusion

In conclusion, the concept of mutability in lists is a fundamental aspect of Python programming. A list in Python is mutable, meaning that its elements can be modified, added, or removed after the list is created. This mutability allows for dynamic changes to the data structure, making lists versatile and flexible for a wide range of applications. Programmers can efficiently manipulate lists, adapting them to evolving requirements in their code. However, it’s essential to exercise caution when working with mutable lists to avoid unintended side effects or unexpected behavior, especially in scenarios involving shared data and concurrent programming. Overall, the mutability of lists in Python is a powerful feature that facilitates dynamic data manipulation and contributes to the language’s ease of use and expressiveness.



Similar Reads

Are Python Lists Mutable
Yes, Python lists are mutable. This means you can change their content without changing their identity. You can add, remove, or modify items in a list after it has been created. Here are some examples demonstrating the mutability of Python lists: Example 1: Creating List[GFGTABS] Python my_list = [1, 2, 3] my_list[1] = 20 # Change the second elemen
2 min read
Use mutable default value as an argument in Python
Python lets you set default values ​​for its parameters when you define a function or method. If no argument for this parameter is passed to the function while calling it in such situations default value will be used. If the default values ​​are mutable or modifiable (lists, dictionaries, etc.), they can be modified within the function and those mo
5 min read
Least Astonishment and the Mutable Default Argument in Python
The principle of Least Astonishment (also known as least surprise) is a design guideline that states that a system should behave the way it is intended to behave. It should not change its behavior in an unexpected manner to astonish the user. By following this principle, designers can help to create user interfaces that are more user-friendly and l
3 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Indexing Lists Of Lists In Python
Lists of lists are a common data structure in Python, providing a versatile way to organize and manipulate data. When working with nested lists, it's crucial to understand how to index and access elements efficiently. In this article, we will explore three methods to index lists of lists in Python using the creation of a sample list, followed by ex
3 min read
The concept of Social Computing in Python
When you try googling something about the thing you may want to know about or just want to recall something, for example, if you are trying to remember a song you listened earlier but failed to recall it, only you can remember about the song is where it was shot then you may not find it by googling it, what you can do is write a post and share it o
2 min read
Background Subtraction in an Image using Concept of Running Average
Background subtraction is a technique for separating out foreground elements from the background and is done by generating a foreground mask. This technique is used for detecting dynamically moving objects from static cameras. Background subtraction technique is important for object tracking. There are several techniques for background subtraction
4 min read
Joint Probability | Concept, Formula and Examples
Probability theory is a cornerstone of statistics, offering a powerful tool for navigating uncertainty and randomness in various fields, including business. One key concept within probability theory is Joint Probability, which enables us to analyse the likelihood of multiple events occurring simultaneously. What is Joint Probability in Business Sta
5 min read