we are going to share how to remove multiple elements from a list in python programming language. If you are a python beginner and want to start learning the python programming, then keep your close attention as we have shared the tutorial to remove multiple elements from a list in python with the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# List of Numbers listOfnum = [12, 44, 56, 45, 34, 3, 4, 33, 44] print("Original List : " , listOfnum) # Remove all numbers from list which are divisible by 3 for elem in listOfnum: if elem % 3 == 0: listOfnum.remove(elem) print("Modified List : " , listOfnum) print("***** Remove multiple elements from list using List Comprehension *****") # List of Numbers listOfnum = [12, 44, 56, 45, 34, 3, 4, 33, 44] print("Original List : " , listOfnum) # Remove all numbers from list which are divisible by 3 listOfnum = [ elem for elem in listOfnum if elem % 3 != 0] print("Modified List : " , listOfnum) print("***** Remove multiple elements from list by index range using del *****") # List of Numbers listOfnum = [12, 44, 56, 45, 34, 3, 4, 33, 44] print("Original List : " , listOfnum) # Removes elements from index 1 to 3 del listOfnum[1:4] print("Modified List : " , listOfnum) if __name__ == '__main__': main() |
Output:
1 2 3 4 5 6 7 8 9 |
Original List : [12, 44, 56, 45, 34, 3, 4, 33, 44] Modified List : [44, 56, 34, 4, 44] Original List : [12, 44, 56, 45, 34, 3, 4, 33, 44] Modified List : [44, 56, 34, 4, 44] Original List : [12, 44, 56, 45, 34, 3, 4, 33, 44] Modified List : [12, 34, 3, 4, 33, 44] |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.