Built with Tutify.io

    AIStudyLabs

    Python List Mutable

    Python List Mutable

    Python lists are mutable data structures, which means you can change or modify their elements after they have been created. This mutability allows the assignment statements toupdate the values of individual elements within the list. This mutability allows you to change, add, or remove elements from a list without creating a new list object.

    In this article, I will explain some list operations and using these how we can update the mutable lists with examples.

    Below are some common list operations to perform on a mutable list:

    <a id="h-1-quick-examples-of-list-mutable"></a>

    1. Quick Examples of List Mutable

    If you are in a hurry, below are some quick examples of the list mutable.

    
    # Quick examples of list mutable
    
    # Example 1: Updating list elements
    mylist = ["Python", "Spark", "Java"]
    mylist[0] = "MangoDB"
    mylist[-1] = "C++"
    
    # Example 2: Modifying an element
    mylist[2] = 10
    
    # Example 3: Appending elements
    mylist.append('Pandas')
    
    # Example 4: Extending with another list
    
    mylist.extend(["C++","Pandas","Java"])
    
    # Example 5: Removing elements
    mylist.remove("Pyspark")
    
    # Example 6: Sort the list ascending order
    mylist.sort()
    
    # Example 7: Sort the list in decending order
    mylist.sort(reverse = True)
    
    # Example 8: Select specified portion of a list
    result = mylist[:2]
    

    <a id="h-2-updating-list-elements"></a>

    2. Updating List Elements

    You can demonstrate the mutability of list by updating elements using the assignment operator. First, initialize a list called mylist with three strings, "Python", "Spark", and "Java". Then, print it as an original list. For example, the code modifies the first and last elements of the list using assignment statements. The line mylist[0] = "MangoDB" assigns the string "MangoDB" to the first element of the list (mylist[0]). The line mylist[-1] = "C++" assigns the string "C++" to the last element of the list (mylist[-1]).

    As you can see, the original list is mutable, allowing you to change its elements using assignment statements. The updated values are reflected in the list after the modifications.

    
    # Initialize list
    mylist = ["Python", "Spark", "Java"]
    print("Original list: ",mylist)
    
    # Updating list elements
    mylist[0] = "MongoDB"
    mylist[-1] = "C++"
    print("After updating the list elements:",mylist)
    

    Yields below output.

    <a id="h-3-modifying-an-element-of-multable-list"></a>

    3. Modifying an Element of Multable List

    You can Modify an element in a list is a common way to demonstrate its mutability. For example, you can start with an initial list mylist containing ["Python", "Spark", "Java"] . Then, you can modify the element at the index 2 (which initially has the value 3) by assigning a new value of 10 to it using the statement mylist[2] = "Pandas".

    As you can see, the original list is mutable, and by modifying the element at index 2, we can change the value from "java" to "Pandas". The updated list reflects the modification. This demonstrates the mutability of lists in Python.

    
    # Initialize list
    mylist = ["Python", "Spark", "Java"]
    print("Original list:", mylist)
    
    # Modifying an element
    mylist[2] = Pandas
    print("After modifying an element:", mylist)
    

    Yields below output.

    <a id="h-4-appending-elements"></a>

    4. Appending Elements

    You can use list.append() method to append an item or element to a list(element can be a string, list e.t.c). For example, if you have a list called mylist and you want to append an element 'Pandas' at the end, use this function. Here, is an example.

    
    # Initialize list
    mylist = ["Python", "Spark", "Java"]
    print("Original list:", mylist)
    
    # Using appending elements
    mylist.append('Pandas')
    print("After updated List:", mylist)
    
    # Output:
    # Original list: ['Python', 'Spark', 'Java']
    # After updated List: ['Python', 'Spark', 'Java', 'Pandas']
    

    <a id="h-5-extending-with-another-list"></a>

    5. Extending with Another List

    By using the list.extend() methodin Python, you can add the elements to the existing list. Note that this modifies the existing list with the new elements and the elements are added at the end of the original list.

    Let’s add the elements from the list to another list.

    
    # Initialize list
    mylist = ["Python", "Spark", "Java"]
    print("Original list:", mylist)
    
    # Extending with another list
    mylist.extend(["C++", "Pandas", "MongoDB"])
    print("After extending the List:", mylist)
    
    # Output:
    # Original list: ['Python', 'Spark', 'Java']
    # After extending the list: ['Python', 'Spark', 'Java', 'C++', 'Pandas', 'MongoDB']
    

    Here, you had four elements in the list and added additional 3 elements from another list. The resultant list contains a total of seven elements.

    6. Removing Elements

    You can use the list.remove() function to remove a specific element from a list. For example, the list.remove() function is used to remove the element "Pyspark" from the list. The function searches for the first occurrence of the specified value and removes it from the list. After removing the element, the list is updated, and the modified list is printed.

    
    # Initialize list
    mylist = ["Python","Spark","Java"]
    print("Original list:", mylist)
    
    # Removing elements
    mylist.remove("Java")
    print("After removing an element from a list:", mylist)
    
    # Output:
    # Original list: ['Python', 'Spark', 'Java']
    # After removing an element from a list: ['Python', 'Spark']
    

    <a id="h-7-sorting-list-elements"></a>

    7. Sorting List Elements

    The Python list.sort() method is a built-in function that is used to sort a list in ascending or descending order. By default, the sort() method sorts the elements of a list in ascending order. However, you can use the reverse parameter to sort the list in descending order.

    
    # Initialize list
    mylist = ["Python","Spark","Java"]
    print("Original list:", mylist)
    
    # Sort the list ascending order
    mylist.sort()
    print("After sorting the list:", mylist)
    
    # Output:
    # Original list: ['Python', 'Spark', 'Java']
    # After sorting the list: ['Java', 'Python', 'Spark']
    
    # Sort the list in decending order
    mylist.sort(reverse = True)
    print("After sorting the list in decending order:", mylist)
    
    # Output:
    # Original list: ['Python', 'Spark', 'Java']
    # After sorting the list in decending order: ['Spark', 'Python', 'Java']
    

    <a id="h-8-slicing-the-list"></a>

    8. Slicing the List

    You can easily slice a listin Python either by using the slice() function or slice notation. These both return a new list that is a subset of the original list. Both these options take start, stop, and step values to split the list.

    
    # Initialize list
    mylist = ["Python","Spark","Java"]
    print("Original list:", mylist)
    
    # Select specified portion of a list
    result = mylist[:2]
    print("After slicing the list:", result)
    
    # Output:
    # Original list: ['Python', 'Spark', 'Java']
    # After slicing the list: ['Python', 'Spark']
    

    Conclusion

    In this article, I have explained Python list mutability and using its mutability nature how we can perform various operations over the list such as updating, modifying, appending, extending, and removing elements.

    Happy Learning !!

    <a id="h-related-articles"></a>

    Related Articles