Write a Python program to delete items using empty list

Different ways to clear a list in Python

There are many ways of clearing the list through methods of different constructs offered by Python language. Let’s try to understand each of the method one by one.

  • Method #1 : Using clear() method




    # Python program to clear a list
    # using clear() method
    # Creating list
    GEEK = [6, 0, 4, 1]
    print('GEEK before clear:', GEEK)
    # Clearing list
    GEEK.clear()
    print('GEEK after clear:', GEEK)

    Output:

    GEEK before clear: [6, 0, 4, 1] GEEK after clear: []

  • Method #2 : Reinitializing the list : The initialization of the list in that scope, initializes the list with no value. i.e list of size 0. Let’s see the example demonstrating Method 1 and 2 to clear list




    # Python3 code to demonstrate
    # clearing a list using
    # clear and Reinitializing
    # Initializing lists
    list1 = [1, 2, 3]
    list2 = [5, 6, 7]
    # Printing list1 before deleting
    print ("List1 before deleting is : "
    + str(list1))
    # deleting list using clear()
    list1.clear()
    # Printing list1 after clearing
    print ("List1 after clearing using clear() : "
    + str(list1))
    # Printing list2 before deleting
    print ("List2 before deleting is : "
    + str(list2))
    # deleting list using reinitialization
    list2 = []
    # Printing list2 after reinitialization
    print ("List2 after clearing using reinitialization : "
    + str(list2))

    Output:

    List1 before deleting is : [1, 2, 3] List1 after clearing using clear() : [] List2 before deleting is : [5, 6, 7] List2 after clearing using reinitialization : []

  • Method #3 : Using “*= 0” : This is a lesser known method, but this method removes all elements of the list and makes it empty.




    # Python3 code to demonstrate
    # clearing a list using
    # *= 0 method
    # Initializing lists
    list1 = [1, 2, 3]
    # Printing list1 before deleting
    print ("List1 before deleting is : " + str(list1))
    # deleting list using *= 0
    list1 *= 0
    # Printing list1 after *= 0
    print ("List1 after clearing using *= 0: " + str(list1))

    Output:

    List1 before deleting is : [1, 2, 3] List1 after clearing using *= 0: []

  • Method #4 : Using del : del can be used to clear the list elements in a range, if we don’t give a range, all the elements are deleted.




    # Python3 code to demonstrate
    # clearing a list using
    # del method
    # Initializing lists
    list1 = [1, 2, 3]
    list2 = [5, 6, 7]
    # Printing list1 before deleting
    print ("List1 before deleting is : " + str(list1))
    # deleting list1 using del
    del list1[:]
    print ("List1 after clearing using del : " + str(list1))
    # Printing list2 before deleting
    print ("List2 before deleting is : " + str(list2))
    # deleting list using del
    del list2[:]
    print ("List2 after clearing using del : " + str(list2))

    Output:

    List1 before deleting is : [1, 2, 3] List1 after clearing using del : [] List2 before deleting is : [5, 6, 7] List2 after clearing using del : []




Article Tags :
Python
Python list-programs
python-list
python-list-functions
Practice Tags :
python-list
Read Full Article

Python – Remove empty List from List

Sometimes, while working with python data, we can have a problem in which we need to filter out certain empty data. These can be None, empty string etc. This can have application in many domains. Let’s discuss certain ways in which removal of empty lists can be performed.

Method #1 : Using list comprehension
This is one of the way in which this problem can be solved. In this, we iterate through the list and don’t include the list which is empty.




# Python3 code to demonstrate
# Remove empty List from List
# using list comprehension
# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
# printing original list
print("The original list is : " + str(test_list))
# Remove empty List from List
# using list comprehension
res = [ele for ele in test_list if ele != []]
# printing result
print ("List after empty list removal : " + str(res))
Output : The original list is : [5, 6, [], 3, [], [], 9] List after empty list removal : [5, 6, 3, 9]

Method #2 : Using filter()
This is yet another way in which this task can be performed. In this we filter None values. The none values include empty lists as well and hence these get removed.




# Python3 code to demonstrate
# Remove empty List from List
# using filter()
# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
# printing original list
print("The original list is : " + str(test_list))
# Remove empty List from List
# using filter
res = list(filter(None, test_list))
# printing result
print ("List after empty list removal : " + str(res))
Output : The original list is : [5, 6, [], 3, [], [], 9] List after empty list removal : [5, 6, 3, 9]




Article Tags :
Python
Python Programs
Python list-programs
Read Full Article

Python List clear()

In this tutorial, we will learn about the Python List clear() method with the help of examples.

The clear() method removes all items from the list.

Example

prime_numbers = [2, 3, 5, 7, 9, 11] # remove all elements prime_numbers.clear()
# Updated prime_numbers List print('List after clear():', prime_numbers)
# Output: List after clear(): []

Different ways to clear a list in Python

PythonServer Side ProgrammingProgramming

Clearing up all the elements in a python list can be done in many ways. Below are the some of the methods which are implemented to achieve this.

Python remove() method

Python removes () method is a built-in method available with the list. It helps to remove the given very first element matching from the list.

Syntax:

list.remove(element)

The element that you want to remove from the list.

ReturnValue

There is no return value for this method.

Tips for using remove() method:

Following are the important points to remember when using remove () method:

  • When the list has duplicate elements, the very first element that matches the given element will be removed from the list.
  • If the given element is not present in the list, it will throw an error saying the element is not in the list.
  • The remove () method does not return any value.
  • The remove () takes the value as an argument, so the value has to pass with the correct datatype.

Example: Using remove() method to remove an element from the list

Here is a sample list that i have

my_list = [12, 'Siya', 'Tiya', 14, 'Riya', 12, 'Riya']

The list has elements of date-types string and number. The list has duplicate elements like number 12 and string Riya.

my_list = [12, 'Siya', 'Tiya', 14, 'Riya', 12, 'Riya'] my_list.remove(12) # it will remove the element 12 at the start. print(my_list) my_list.remove('Riya') # will remove the first Riya from the list print(my_list) my_list.remove(100) #will throw an error print(my_list)

Output:

['Siya', 'Tiya', 14, 'Riya', 12, 'Riya'] ['Siya', 'Tiya', 14, 12, 'Riya'] Traceback (most recent calllast): File "display.py", line 9, in <module> my_list.remove(100) ValueError: list.remove(x): x not in the list

Methods:

Many methods exist in Python to modify the list. Some common methods to add and remove data in the list are mentioned here.

insert (index,item): This method is used to insert any item in the particular index of the list and right shift the list items.

append (item): This method is used to add new element at the end of the list.

extend (anotherList): The items of one list can be inserted at the end of another list by using this method.

remove (item): This method is used to remove particular item from the list.

pop (index): The method is used to remove item from the list based on index value.

del(): This method is used to remove the particular item of the list or slice the list.

clear(): This method is used to remove all items of a list

Add items into the list:

Different ways to add items in Python list are shown in this part of the tutorial.

Example 1: Insert item using insert() method

Create a python file with the following script to see the use of insert() method. A new item will be inserted in the third position of the list and the other items will be shifted right after running the script.

# Declare list
listdata = [89, 56, 90, 34, 89, 12]

# Insert data in the 2nd position
listdata.insert(2, 23)

# Displaying list after inserting
print("The list elements are")

for i in range(0, len(listdata)):
print(listdata[i])

Output:

The following output will appear after running the script.

Example 2: Insert item using append() method

Create a python file with the following script to see the use of append() method. It is mentioned before that append() method inserts data at the end of the list. So, ‘Toshiba’ will be inserted at the end of listdata after running the script.

# Define the list
listdata = ["Dell", "HP", "Leveno", "Asus"]

# Insert data using append method
listdata.append("Toshiba")

# Display the list after insert
print("The list elements are")

for i in range(0, len(listdata)):
print(listdata[i])

Output:

The following output will appear after running the script.

Example 3: Insert item using extend() method

Create a python file with the following script to see the use of extend() method. Here, two lists are declared in the script which are combined together by using extend() method. The items of the second list will be added at the end of the first list.

# initializing the first list
list1 = ['html', 'CSS', 'JavaScript', 'JQuery']

# initializing the second list
list2 = ['PHP', 'Laravel', 'CodeIgniter']

# Combine both lists using extend() method
list1.extend(list2)

# Display the list after combing
print ("The list elements are :")

for i in range(0, len(list1)):
print(list1[i])

Output:

The following output will appear after running the script.

Python remove empty elements from a list Example

Simple examples code.

Using list comprehension

Simp;e iterate through the list and add the non-empty elements.

list1 = ['A', ' ', ' ', 'B', ' ', 'C'] res = [ele for ele in list1 if ele.strip()] print(res) list2 = [1, 6, [], 3, [], [], 9] res = [ele for ele in list2 if ele != []] print(res)

Output:

1. Using list.clear() function

list.clear() is the recommended solution in Python 3 to remove all items from the list.

1
2
3
4
5
6
7
8
if __name__ == '__main__':
a = [1, 2, 3, 4, 5]
print(a)# prints [1, 2, 3, 4, 5]
a.clear()
print(a)# prints []

DownloadRun Code

Video liên quan

Postingan terbaru

LIHAT SEMUA