Blog

  • Python List copy() Method

    In Python, the copy() method is a list method used to create a shallow copy of a list. The list copy() method creates a new list consisting of the same elements as the original list; however, it maintains its own identity in the memory. It is useful when we want to make sure that the changes to the new list do not affect the original list and vice versa.

    Syntax of the Python List copy() Method

    The following is the syntax of the Python list copy() method:

    new_list = original_list.copy()    

    Parameter

    • The copy() method does not take any parameters.

    Return Value

    • The copy() method returns a shallow copy of a list.

    Examples of List copy()

    We will now take a look at some examples of the list copy() method in Python.

    Example 1: Working of the copy() Method

    In the following example, we will understand the working of the copy() method to create a shallow copy of a given list.

    Example

    # Simple example of List copy() Method  
    
      
    
    # given list  
    
    car_list = ["Tata", "Honda", "Mahindra", "Toyota", "BMW"]  
    
    print("Given List:", car_list)  
    
      
    
    # creating a copy of a list using copy()  
    
    newcar_list = car_list.copy()  
    
    print("Copied List:", newcar_list)

    Output:

    Given List: ['Tata', 'Honda', 'Mahindra', 'Toyota', 'BMW']
    Copied List: ['Tata', 'Honda', 'Mahindra', 'Toyota', 'BMW']
    

    Explanation:

    In the above example, we are given a list. We used the copy() method to create a shallow copy of the given list and stored the generated list in a new variable, newcar_list.

    As a result, we have successfully copied the content of the given list to a new list.

    Example 2: Modifying the Copied List

    We will now look at an example to see what happens when we try modifying the copied list.

    Example

    # Simple example of List copy() Method  
    
      
    
    # given list  
    
    car_list = ["Tata", "Honda", "Mahindra", "Toyota", "BMW"]  
    
      
    
    # creating a copy of a list using copy()  
    
    newcar_list = car_list.copy()  
    
      
    
    # modifying the copied list  
    
    newcar_list.append("Audi")  
    
      
    
    # printing results  
    
    print("Given List:", car_list)  
    
    print("Modified List:", newcar_list)

    Output:

    Given List: ['Tata', 'Honda', 'Mahindra', 'Toyota', 'BMW']
    Modified List: ['Tata', 'Honda', 'Mahindra', 'Toyota', 'BMW', 'Audi']
    

    Explanation:

    In this example, we are given a list. We used the copy() method to copy the list and stored in a variable, newcar_list. We then used the append() method to add a new element to the copied list.

    As a result, after appending ‘Audi’ to newcar_list, the original list remains unchanged. This shows that both the lists are independent.

    Example 3: Copying a List of Lists

    Even though the copy() method allows us to create a new list; however, it is a shallow copy. Modifying the inner list in copied list also affects original list as both lists reference the same inner lists.

    Example

    # Simple example of List copy() Method  
    
      
    
    # given list  
    
    matrix = [  
    
        [1, 3],   
    
        [5, 2]  
    
        ]  
    
      
    
    # creating a copy of a list using copy()  
    
    new_matrix = matrix.copy()  
    
      
    
    # modifying the copied list  
    
    new_matrix[0][0] = 99  
    
    print("Given List:", matrix)  
    
    print("Modified List:", new_matrix)

    Output:

    Given List: [[99, 3], [5, 2]]
    Modified List: [[99, 3], [5, 2]]
    

    Explanation:

    In the above example, we are given a list of lists. We used the copy() method to create a shallow copy of the given list. We then modified an element of the nested list of the copied list.

    Although both the lists are separate lists, the nested lists inside them are still share the same reference. Therefore, modifying a nested item in the copied list also affects the original list. This is what makes it a shallow copy.

    Example 4: Copying a List of Mixed Data Types

    In the following example, we will create a shallow copy of a list consisting of multiple data types, such as numbers, strings, lists, and dictionaries.

    Example

    # Simple example of List copy() Method  
    
      
    
    # given list  
    
    mixed_list = [10, 'Hello', 2.4, [3, 6], {'python' : 'app'}]  
    
      
    
    # creating a copy of a list using copy()  
    
    new_mixed_list = mixed_list.copy()  
    
      
    
    # modifying the copied list  
    
    new_mixed_list[3].append(11)  
    
      
    
    # printing results  
    
    print("Given List:", mixed_list)  
    
    print("Modified List:", new_mixed_list)

    Output:

    Given List: [10, 'Hello', 2.4, [3, 6, 11], {'python': 'app'}]
    Modified List: [10, 'Hello', 2.4, [3, 6, 11], {'python': 'app'}]
    

    Explanation:

    In the above example, we are given a list of mixed data types. We used the copy() method to create a shallow copy of the given list. We then modified the nested list of the copied list by appending a new element to it.

    Although both the lists are different, the lists inside them are still share the same reference. So when 11 is appended to new_mixed_list[3], it also changes mixed_list[3].

    Conclusion

    Python contains different built-in methods and functions that help developers to easily create flawless software. The Python list copy() method is extremely useful in situations where we want to create a shallow copy. This tutorial has covered all the details and examples regarding this method, but don’t limit to these examples; instead, try more and more examples to be proficient.

  • Python List sort() Method

    The Python list sort() method is an inbuilt method that allows the user to sort the elements of the list either in ascending or descending order. This function doesn’t return any value because no new list is created instead, it modifies the list and replaces it with the current one. The sort() function is a useful method as it helps the developers to arrange the list in numeric or alphabetical order.

    Syntax of the sort() Method in Python List

    The following is the syntax of the list sort() method:

    list_name.sort(key = None, reverse = False)  

    Parameter

    • key (Optional):This parameter allows the user to specify a function to be used for sorting criteria. For example, if you want to sort the list on the basis of its length you can simple use the len() function.
    • reverse (Optional):Its takes Boolean If you set the reverse argument to Boolean True, the list would be sorted in descending order, else it would sort the list in ascending order. By default, it is set to False.

    Return

    The sort() method in Python returns none.

    Examples of List sort()

    We will now take a look at some examples of the list sort() method in Python.

    Example 1: Sort List in Ascending Order

    In the following example, we will understand the working of the sort() method to sort a given list in ascending order.

    Example

    lst_1 = [1,5,7,0,10,14]  
    
    # Sort the value in ascending order  
    
    lst_1.sort()  
    
    print(lst_1)

    Output:

    [0, 1, 5, 7, 10, 14]

    Explanation:

    In the above example, we have sorted the given list in ascending order using the sort() method.

    Example 2: Sort List in Descending Order

    We can sort the given list in descending order by setting the reverse argument of the sort() method to True, as shown in the following example:

    Example

    # given list  
    
    lst_1 = [1,5,7,0,10,14]  
    
    # Sort the value in descending order  
    
    lst_1.sort(reverse = True)  
    
    print(lst_1)

    Output:

    [14, 10, 7, 5, 1, 0]

    Explanation:

    In this example, we have reversed the order of the sorted list by setting the reverse parameter to True.

    Example 3: Sort a List in order of the Length of the Values

    We will create a function and sort the given list in order of the length of the values as shown in following example:

    Example

    # defining a function that returns the length of each element  
    
    def newFunc(e):  
    
      return len(e)  
    
      
    
    # creating the list  
    
    fruits = ['Apple', 'Strawberry', 'Melon', 'Orange']  
    
      
    
    # sorting the fruits names in ascending of the length of the fruits name  
    
    fruits.sort(key = newFunc)  
    
      
    
    # printing the fruits name  
    
    print(fruits)

    Output:

    ['Apple', 'Melon', 'Orange', 'Strawberry']

    Explanation:

    Here, we have used the key parameter in sort() method and set it to the function, we defined. This function returns the length of each element present in the list and sort them accordingly in ascending order.

    Things to Remember

    1. The Python sort() method is used to modify the list in place.
    2. The Python sort() method returns None.
    3. By default, the sort() function sorts the list in ascending order. You can also sort the list in descending order, all you need to do is to set the reverse parament to true.
    4. The key parameter can be used for customizing the sorting criteria.
    5. We can use the sort() method, if we need to create a new sorted list without changing the original list.
    6. By default, the sort() method is case sensitive. It means all the capital letters will be sorted before.

    Conclusion

    Python contains different built-in methods and functions that help developers to easily create flawless software. The Python list sort() method is extremely useful in situations where you want to quickly sort the list alphabetically, numerically, whether in ascending order or descending order. This tutorial has covered all the details and examples regarding this method, but don’t limit yourself to these examples; instead, try more and more examples to be proficient.

  • Python list index() method

    The Python list index() method is useful in situations where the user wants to look for the position of a required item in the given list. This method starts the search from its first element, and continues until it finds the position of the first occurrence of the element.

    Note: This method returns the position of only the first occurrence of the element and return a ValueError if the element is not found in the specified range.

    Syntax of the index() Method in Python List

    The following is the syntax of the list index() method:

    list.index(elmnt, start, end)  

    Parameters

    • elmnt (Required) : This parament looks the elements to search for. It accepts any type of variable such as string, number, list, etc.
    • start (Optional): It takes the value representing the position from where the user wants to start the search.
    • end (Optional): This parameter takes a number value representing the position from where to end the search.

    Returns

    The index() method returns the position at the first occurrence of the given value. If the element is not found it returns ValueError error.

    Examples of List index()

    We will now take a look at some examples of the list index() method in Python.

    Example 1: Find Position of an Element in a List

    In this example, we will see how the index() method works in finding the position of the specified element in the given list.

    Example

    # given lists  
    
    num_list = [12, 13, 9, 10, 7, 2]  
    
    fruit_list = ['apple', 'banana', 'mango', 'banana', 'cherry', 'grapes']  
    
      
    
    # using the index() method  
    
    print("The index of 10 is:", num_list.index(10))  
    
    print("The index of 'cherry' is:", fruit_list.index('cherry'))

    Output:

    The index of 10 is: 3
    The index of 'cherry' is: 4
    

    Explanation:

    Here, we have used the index() method to find the index of the first occurrence of the specified elements in the given lists.

    Example 2: Find Position of an Element in a List from a Specified Starting Index

    We will now take a look at an example to find the position of an element in a given list. But it will not start from 0, instead we will specify the starting point for the search.

    Example

    # given lists  
    
    list_1 = [19, 11, 21, 16, 11, 15, 29]  
    
    list_2 = ['red', 'green', 'blue', 'yellow', 'purple', 'red', 'pink', 'orange']  
    
      
    
    # using the index() method  
    
    print("The index of 11 starting from index 3 is:", list_1.index(11, 3))  
    
    print("The index of 'red' starting from index 4 is:", list_2.index('red', 4))

    Output:

    The index of 11 starting from index 3 is: 4
    The index of 'red' starting from index 4 is: 5
    

    Explanation:

    In this example, we specified the start index in the index() method to find the first occurrence of the elements in the given lists starting from that index.

    Example 3: Find Position of an Element in a List between a Specified range

    This example will show how to use the index() method to find the position of an element in a given list in a specific range.

    Example

    # given lists  
    
    list_1 = ['red', 'blue', 'green', 'yellow', 'blue', 'white', 'black', 'grey', 'pink']  
    
    list_2 = [0, 1, 11, 4, 12, 5, 6, 3, 12, 11, 5, 7]  
    
      
    
    # using the index() method  
    
    print("The index of 'blue' between 2nd and 6th index is:", list_1.index('blue', 2, 6))  
    
    print("The index of 12 between 6th and 9th index is:", list_2.index(12, 6, 9))

    Output:

    The index of 'blue' between 2nd and 6th index is: 4
    The index of 12 between 6th and 9th index is: 8
    

    Explanation:

    Here, we specified the start and end index to search for the specified elements in the given lists between that particular ranges.

    Example 4: Find Position an Element that is Not Present in the List

    We will now look at an example, where we will try to return the position of an element which is not a part of the given list.

    Example

    # given list  
    
    list_1 = ['blue', 'red', 'green', 'yellow', 'orange', 'white', 'black', 'grey']  
    
      
    
    try:  
    
      # using the index() method  
    
      print("The index of 'pink' is:", list_1.index('pink'))  
    
    except ValueError:  
    
      print("'pink' is not present in the list")

    Output:

    'pink' is not present in the list

    Explanation:

    In the above example, we have used the ‘try…except’ block to handle ValueError. Inside the ‘try’ block we called the index() method to find the index of an element within the given list. Since the specified element is not found in the list, it raised ValueError which is handled by the ‘except’ block and a message is printed for us.

    Conclusion

    The Python index() method is a helpful tool for finding any particular element in a list. It contains three parameters and provides the flexibility to choose the start and ending positions of the element. The developers use this method to manage and look for data in the list.

  • Python List insert() Method

    In Python, the list insert() method is used to insert the element at the specified index in the list. The first argument is the index of the element before which to insert the element.

    Syntax of the insert() Method in Python List

    The following is the syntax of the list insert() method:

    insert(i, x)   
    

    Parameter(s)

    • i: index at which element would be inserted.
    • x: element to be inserted.

    Return

    • It does not return any value rather modifies the list.

    Examples of List insert()

    Let’s see some examples of insert() method to understand it’s functionality.

    Example 1: Inserting an Element to a List

    Let’s see an example to insert an element at a specific position in the list.

    Example

    # given list  
    
    lst_1 = [12, 4, 19, 22, 5]  
    
    print("Given List:", lst_1)  
    
      
    
    # using insert() to add an element to the list  
    
    lst_1.insert(3, 14)  
    
    print("Updated List:", lst_1)

    Output:

    Given List: [12, 4, 19, 22, 5]
    Updated List: [12, 4, 19, 14, 22, 5]
    

    Explanation:

    In this example, we are given a list. We used the insert() method to insert an element – 14 at the index value – 3. As a result, the list is updated with the inserted element.

    Example 2: Inserting a List in a List

    It is possible to insert a list as an element to the list. Let us see an example where a list is inserted at specified index.

    Example

    # given list  
    
    lst_1 = [13, 11, 9, 1, 6]  
    
    print("Given List:", lst_1)  
    
      
    
    # second list  
    
    lst_2 = [3, 12, 14]  
    
      
    
    # using insert() to add a list in the list  
    
    lst_1.insert(2, lst_2)  
    
    print("Updated List:", lst_1)

    Output:

    Given List: [13, 11, 9, 1, 6]
    Updated List: [13, 11, [3, 12, 14], 9, 1, 6]
    

    Explanation:

    In this example, we are given two lists. We used the insert() function to insert the second list in the first list at the index – 2. As a result, the list is inserted successfully.

    Example 3: Inserting a Tuple to a List

    In Python, it is possible to insert a tuple as an element to the list. Here is an example to insert the tuple in the given at specified index.

    Example

    # given list  
    
    lst_1 = [12, 22, 14, 9, 5]  
    
    print("Given List:", lst_1)  
    
      
    
    # given tuple  
    
    tpl_1 = (1, 7, 6)  
    
      
    
    # using insert() to add a tuple in the list  
    
    lst_1.insert(2, tpl_1)  
    
    print("Updated List:", lst_1)

    Output:

    Given List: [12, 22, 14, 9, 5]
    Updated List: [12, 22, (1, 7, 6), 14, 9, 5]
    

    Explanation:

    In this example, we are given a list and a tuple. We used the insert() method to insert the tuple in the given list at the index – 2. As a result, the tuple is inserted to the list successfully.

    Example 4: Inserting a Set to a List

    In Python, we can insert a set as an element to the list. Here is an example showing how to insert a set in the list at a specific index.

    Example

    # given list  
    
    lst_1 = [10, 18, 25, 19, 34]  
    
    print("Given List:", lst_1)  
    
      
    
    # given set  
    
    set_1 = {14, 17, 6}  
    
      
    
    # using insert() to add a set in the list  
    
    lst_1.insert(3, set_1)  
    
    print("Updated List:", lst_1)

    Output:

    Given List: [10, 18, 25, 19, 34]
    Updated List: [10, 18, 25, {17, 14, 6}, 19, 34]
    

    Explanation:

    In the above example, we are given a list and set. We used the insert() method to insert the set in the list at index – 3. As a result, the set is inserted successfully.

    Conclusion

    The insert() is a list method in Python that adds an element in a specific position, modifying the original list. It can append numbers, strings, or even other lists, creating nested structures. This method is useful for dynamically growing lists while maintaining the list’s original order.

  • Python List pop() Method

    In Python, the pop() method is used to remove the element from the list present at the given index. This method also returns the removed element. If the index is unspecified, it will remove and return the last element by default.

    This method is specifically convenient when we are required to manipulate a list dynamically, as it directly modifies the original list.

    Syntax of the Pop() Method in Python List

    The following is the syntax of the pop() method:

    pop([idx])       

    Parameters

    • idx(optional): This parameter represents the element to be popped. The default value is -1, which means it would return the last element of the list.

    Return

    • The popped element is returned.

    Examples of List pop()

    We will now take a look at some examples of the list pop() method in Python:

    Example 1: Simple Use Case of the pop() Method

    Let us see a simple example to understand the working of list pop() method.

    Example

    # Simple Example of list pop() Method      
    
    # given list      
    
    lst_1 = [19, 3, 14, 7, 22, 5]    
    
    print("Given List:", lst_1)    
    
    print()    
    
        
    
    # using pop() method to remove and return the element    
    
    print("Popped Element:", lst_1.pop()) # since no argument is defined, it will pop last element    
    
    print("List after Popping:", lst_1)    
    
    print()    
    
        
    
    # using pop() method again    
    
    print("Popped Element:", lst_1.pop())    
    
    print("List after Popping:", lst_1)

    Output:

    Given List: [19, 3, 14, 7, 22, 5]
    
    Popped Element: 5
    List after Popping: [19, 3, 14, 7, 22]
    
    Popped Element: 22
    List after Popping: [19, 3, 14, 7]
    

    Explanation:

    In this example, we are given a list consisting some elements. We used the pop() method to remove the element. Since, we have not specified the index value, the last element will be removed. We again performed the same operation.

    As a result, the pop() method popped the last element from the list, every time it is called.

    Example 2: Popping the Specific Element from the List

    We will now take a look at an example to understand how to remove a specific element from the list.

    Example

    # Simple Example of list pop() Method      
    
    # given list      
    
    lst_1 = [19, 3, 14, 7, 22, 5]    
    
    print("Given List:", lst_1)    
    
    print()    
    
        
    
    # using pop() method to remove and return the element    
    
    print("Popped Element:", lst_1.pop(2)) # since index=2 is specified, the element 14 will be popped    
    
    print("List after Popping:", lst_1)    
    
    print()    
    
        
    
    # using pop() method again    
    
    print("Popped Element:", lst_1.pop(0)) # index=0, element = 19 popped    
    
    print("List after Popping:", lst_1)

    Output:

    Given List: [19, 3, 14, 7, 22, 5]
    
    Popped Element: 14
    List after Popping: [19, 3, 7, 22, 5]
    
    Popped Element: 19
    List after Popping: [3, 7, 22, 5]
    

    Explanation:

    In this example, we are given a list consisting some elements. We used the pop() method to remove the particular element by specifying the index values like 2 and 0,

    As a result, 14 and 19 is popped from the given list.

    Example 3: Removing the Elements from the Last

    We can remove the elements from the last of the list by specifying the index value as a negative integer. Let us see an example:

    Example

    # Simple Example of list pop() Method    
    
        
    
    # given list      
    
    lst_1 = [19, 3, 14, 7, 22, 5]    
    
    print("Given List:", lst_1)    
    
    print()    
    
        
    
    # using pop() method to remove and return the element    
    
    print("Popped Element:", lst_1.pop(-1)) # since index=-1 is specified, the element 5 will be popped    
    
    print("List after Popping:", lst_1)    
    
    print()    
    
        
    
    # using pop() method again    
    
    print("Popped Element:", lst_1.pop(-4)) # index=-4, element = 3 popped    
    
    print("List after Popping:", lst_1)

    Output:

    Given List: [19, 3, 14, 7, 22, 5]
    
    Popped Element: 5
    List after Popping: [19, 3, 14, 7, 22]
    
    Popped Element: 3
    List after Popping: [19, 14, 7, 22]
    

    Explanation:

    In this example, we are given a list consisting some elements. We used the pop() method to remove the particular element by specifying the index values -1, and -4.

    As a result, 5 and 3 is popped from the given list.

    Conclusion

    The pop() method is a useful list method. It allows the developers to remove an item from the list by specifying its index value. If the user doesn’t specify a value for the index parameter, the pop() method defaults to removing the last value from the list. In this tutorial, we have covered the explanation of this method, its syntax, and various examples that will help you better understand this method.

  • Python List count() Method

    In Python, the list count() method is used to return the number of times an element appears in the list. If the element is not present in the list, it returns 0.

    Syntax of the count() Method in Python List

    The following is the syntax of the list count() method:

    count(x)     

    Parameters

    • x: element to be counted.

    Return

    • It returns number of times x occurred in the list.

    Examples of Python List count() Method

    Let’s see some examples of the count() method to understand it’s working.

    Example 1: Finding the Occurrence of an Element in a List

    In this example, we will understand the use of the count() method to find the total occurrence of an element in the given list.

    Example

    # given list  
    
    fruits = ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon']  
    
    print("Given List:", fruits)  
    
      
    
    # using count() method  
    
    total_occurrence = fruits.count('banana')  
    
      
    
    # printing results  
    
    print("Count of 'banana' =", total_occurrence)

    Output:

    Given List: ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon']
    Count of 'banana' = 3
    

    Explanation:

    In this example, we are given a list consisting of some elements. We used the count() method to count the occurrence of a specific element in the list. Since element ‘banana’ is occurred 3 times in the list, the count() method returned 3.

    Example 2: Counting an Element Not Present in the List

    If the passed value is not present in the list, the count() method returns 0.

    Here is an example:

    Example

    # given list  
    
    fruits = ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon']  
    
    print("Given List:", fruits)  
    
      
    
    # using count() method  
    
    total_occurrence = fruits.count('kiwi')  
    
      
    
    # printing results  
    
    print("Count of 'kiwi' =", total_occurrence)

    Output:

    Given List: ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon']
    Count of 'kiwi' = 0
    

    Explanation:

    In this example, we are given a list consisting of some elements. We used the count() method to count the occurrence of a specific element in the list. Since element ‘kiwi’ is not a part of the list, the count() method returned 0.

    Example 3: Checking If an Element in the List is Duplicate

    The count() method can be used to check if any duplicate elements are present in the list. Here is an example:

    Example

    # given list  
    
    fruits = ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon']  
    
    print("Given List:", fruits)  
    
      
    
    # using count() method  
    
    total_occurrence = fruits.count('banana')  
    
          
    
    # checking if the element is duplicate or not  
    
    if total_occurrence >= 2:  
    
      print("The value 'banana' is duplicate.")  
    
      print("Count of 'banana' =", total_occurrence)  
    
    else:  
    
      print("The value 'banana' is not duplicate.")

    Output:

    Given List: ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon']
    The value 'banana' is duplicate.
    Count of 'banana' = 3
    

    Explanation:

    Here, we are given a list consisting of some elements. We used the count() method to count the occurrence of a specific element in the list. We then checked if the returned number is higher or equal to 2 for duplicate elements.

    Since, the banana is present in the list for 3 times, the message “The value ‘banana’ is duplicate” is printed.

    Conclusion

    The List count() method in Python is a useful tool frequently used by developers to return the number of times an element appears in the list. It is helpful to find the duplicate values and validate the list data. The count() method is case-sensitive and returns 0 if the value is not found. The developers use this method to search for exact matches and to manage the list data.

  • Python List clear() Method

    The Python list clear() method removes all the elements from the list. It clear the list completely and returns nothing. It does not require any parameter and returns no exception if the list is already empty.

    Syntax of the clear() Method in Python List

    The following is the syntax of the list clear() method:

    clear()  

    Parameter

    • No parameter

    Return

    • It returns None.

    Examples of List clear()

    Let’s see some examples of list clear() method to understand it’s functionality.

    Example 1: Simple Use of the List clear() Method

    Let’s see a simple example in which clear() method is used to clear a list. The clear() method clears all the elements from the list.

    Example

    # Python List clear() Method  
    
      
    
    # given list  
    
    lst_1 = ['1','2','3']  
    
    print("Given List:", lst_1)  
    
      
    
    # clearing the list  
    
    lst_1.clear()  
    
    print("Updated List:", lst_1)

    Output:

    Given List: ['1', '2', '3']
    Updated List: []
    

    Explanation:

    In the above example, we are given a list. We used the clear() method to remove all the elements from the list. As a result, the list becomes empty.

    Example 2: Clearing an Empty List

    If the list is already empty, the method returns nothing. See the example below.

    Example

    # Python List clear() Method  
    
      
    
    # given list  
    
    lst_1 = []  
    
    print("Given List:", lst_1)  
    
      
    
    # clearing the list  
    
    lst_1.clear()  
    
    print("Updated List:", lst_1)

    Output:

    Given List: []
    Updated List: []
    

    Explanation:

    In this example, we are given an empty list. We used the clear() method to clear the list. Since, the list is already empty, there is no impact on the list after using clear(). Hence, it returns nothing.

    Conclusion

    Python contains different built-in methods and functions that help developers to easily create flawless software. The Python list clear() method is extremely useful in situations where we want to quickly empty the list. This tutorial has covered all the details and examples regarding this method, but don’t limit yourself to these examples; instead, try more and more examples to be proficient.

  • Python List append() Method

    Python list append() method adds an item to the end of the list. It appends an element by modifying the list. The method does not return itself. The item can also be a list or dictionary which makes a nested list.

    Syntax of the sort() Method in Python List

    The following is the syntax of the list sort() method:

    append(x)  

    Parameter(s)

    • x:It can be a number, list, string, dictionary etc.

    Return

    • It does not return any value rather modifies the list.

    Examples of List append()

    Let’s see some examples of the append() method to understand it’s functionality.

    Example 1: Adding an Element to the List

    First, let’s see a simple example which appends elements to the list.

    Example

    # given list  
    
    lst_1 = [12, 16, 20, 24]  
    
    print("Given List:", lst_1)  
    
      
    
    # adding a new element to the list  
    
    lst_1.append(28)  
    
    print("Updated List:", lst_1)

    Output:

    Given List: [12, 16, 20, 24]
    Updated List: [12, 16, 20, 24, 28]
    

    Explanation:

    Here, we are given a list consisting of some elements. We used the append() method to add a new element, 28, to the list. As a result, the element is added at the last of the list.

    Example 2: Adding a list to a list

    In Python, we can append a list to a list making it a nested list. Here is an example to understand how to do it using list append() method.

    Example

    # given lists  
    
    lst_1 = [11, 15, 19]  
    
    lst_2 = [10, 20, 30]  
    
      
    
    print("List 1:", lst_1)  
    
    print("List 2:", lst_2)  
    
      
    
    # adding a list to the list  
    
    lst_1.append(lst_2)  
    
    print("Nested List:", lst_1)

    Output:

    List 1: [11, 15, 19]
    List 2: [10, 20, 30]
    Nested List: [11, 15, 19, [10, 20, 30]]
    

    Explanation:

    In the above example, we are given two lists consisting of some elements. We used the append() method to add the second list to the first list. This creates a nested list.

    Example 3: Appending Multiple Lists to a Single List

    Appending multiple lists to the single list will create a nested list. Here, two lists are appended to the same list and generates a list of the multiple lists. See the example below to understand about the nested list.

    Example

    # given lists  
    
    lst_1 = [11, 15, 19]  
    
    lst_2 = [10, 20, 30]  
    
      
    
    print("List 1:", lst_1)  
    
    print("List 2:", lst_2)  
    
      
    
    # adding a list to the list  
    
    lst_1.append(lst_2)  
    
      
    
    # adding elements to the second list  
    
    lst_2.append([15, 30, 45])  
    
      
    
    print("Nested List:", lst_1)

    Output:

    List 1: [11, 15, 19]
    List 2: [10, 20, 30]
    Nested List: [11, 15, 19, [10, 20, 30, [15, 30, 45]]]
    

    Explanation:

    In this example, we are given multiple lists. We used the append() method to append the second list to the first list. We then again used the append() method to add a new list to the second list. As a result, the first list is also updated showing the nested list.

    Conclusion

    The append() method in Python adds a single element to the end of a list, modifying the original list. It can append numbers, strings, or even other lists, creating nested structures. This method is useful for dynamically growing lists while maintaining the list’s original order.

  • Python String isidentifier() Method

    Python isidentifier() method is used to check whether a string is a valid identifier or not. It returns True if the string is a valid identifier otherwise returns False.

    Python language has own identifier definition which is used by this method.

    Syntax of Python String isidentifier() Method

    It has the following syntax:

    isidentifier()  

    Parameters

    No parameter is required.

    Return

    It returns either True or False.

    Different Examples for Python String isidentifier() Method

    Let’s see some examples of isidentifier() method to understand it’s functionalities.

    Example 1

    A simple Example to apply isidentifier() method, it returns True. See the example.

    # Python isidentifier() method example  
    
    # Variable declaration  
    
    str = "abcdef"  
    
    # Calling function  
    
    str2 = str.isidentifier()  
    
    # Displaying result  
    
    print(str2)

    Output:

    True
    

    Example 2

    Here, we have created variety of identifiers. Some returns True and some False. See the example below.

    # Python isidentifier() method example  
    
    # Variable declaration  
    
    str = "abcdef"  
    
    str2 = "20xyz"  
    
    str3 = "$abra"  
    
    # Calling function  
    
    str4 = str.isidentifier()  
    
    str5 = str2.isidentifier()  
    
    str6 = str3.isidentifier()  
    
    # Displaying result  
    
    print(str4)  
    
    print(str5)  
    
    print(str6)

    Output:

    True
    False
    False
    

    Example 3

    This method is useful in decision making therfore can be used with if statement.

    # Python isidentifier() method example  
    
    # Variable declaration  
    
    str = "abcdef"  
    
    # Calling function  
    
    if str.isidentifier() == True:  
    
        print("It is an identifier")  
    
    else:  
    
        print("It is not identifier")  
    
    str2 = "$xyz"  
    
    if str2.isidentifier() == True:  
    
        print("It is an identifier")  
    
    else:  
    
        print("It is not identifier")
  • Python String isdigit() Method

    Python isdigit() method returns True if all the characters in the string are digits. It returns False if no character is digit in the string.

    Python String isdigit() Method Syntax

    It has the following syntax:

    isdigit()  

    Parameters

    No parameter is required.

    Return

    It returns either True or False.

    Different Examples for Python String isdigit() Method

    Let’s see some examples of isdigit() method to understand it’s functionalities.

    Example 1

    A simple example of digit testing using isdigit() method.

    # Python isdigit() method example  
    
    # Variable declaration  
    
    str = '12345'  
    
    # Calling function  
    
    str2 = str.isdigit()  
    
    # Displaying result  
    
    print(str2)

    Output:

    True
    

    Example 2

    It returns true only if all the characters are digit. See the example below.

    # Python isdigit() method example  
    
    # Variable declaration  
    
    str = "12345"  
    
    str3 = "120-2569-854"  
    
    # Calling function  
    
    str2 = str.isdigit()  
    
    str4 = str3.isdigit()  
    
    # Displaying result  
    
    print(str2)  
    
    print(str4)

    Output:

    True
    False
    

    Example 3

    We can use it in programming to check whether a string contains digits or not.

    # Python isdigit() method example  
    
    # Variable declaration  
    
    str = "123!@#$"  
    
    if str.isdigit() == True:  
    
        print("String is digit")  
    
    else:  
    
        print("String is not digit")

    Output:

    String is not digit