- Python Basic Programs
- Python Program Examples
- Python Print Hello World
- Python Get Input from User
- Python Add Two Numbers
- Add Subtract Multiply Divide
- Python Check Even or Odd
- Python Check Prime or Not
- Python Check Alphabet or Not
- Python Check Vowel or Not
- Python Check Leap Year or Not
- Check Reverse equal Original
- Check Positive Negative Zero
- Python Check Armstrong or Not
- Python Check Palindrome or Not
- Python Check Perfect Number
- Python Find Reverse of Number
- Python Count Digits in Number
- Python Add Digits of Number
- Sum of First and Last Digits
- Python Product of Mid Digits
- Sum of Squares of Digits
- Interchange Digits of Number
- Python Sum of n Numbers
- Python Print ASCII Values
- Python Swap Two Numbers
- Python Swap Two Variables
- Python Fahrenheit to Celsius
- Python Celsius to Fahrenheit
- Python Display Calendar
- Python Days into Years, Weeks
- Find Largest of Two Number
- Find Largest of Three Number
- Python Print Fibonacci Series
- Generate Armstrong Numbers
- Python Make Simple Calculator
- Python Add Binary Numbers
- Binary Number Multiplication
- Python Mathematical Programs
- Find Sum of Natural Numbers
- Find Average of n Numbers
- Python Print Multiplication Table
- Print Table using Recursion
- Python Find Average Percentage
- Python Find Grade of Student
- Find Square Root of Number
- Python Print Prime Numbers
- Find Numbers Divisible by
- Python Find Factors of Number
- Python Find Factorial of a Number
- Python Find HCF & LCM
- Python Kilometres to Miles
- Python Find Area of Square
- Python Find Area of Rectangle
- Python Find Area of Triangle
- Python Find Area of Circle
- Python Find Perimeter of Square
- Find Perimeter of Rectangle
- Python Find Perimeter of Triangle
- Find Circumference of Circle
- Python Simple Interest
- Python Solve Quadratic Equation
- Python Different Set of Operations
- Python Display Powers of 2
- Python Find nCr & nPr
- Python Pattern Programs
- Python Print Pattern Programs
- Python Print Diamond Pattern
- Python Print Floyd's Triangle
- Python Print Pascal's Triangle
- Python List Programs
- Python Count Even/Odd in List
- Python Positive/Negative in List
- Python Even Numbers in List
- Python Odd Numbers in List
- Python Sum of Elements in List
- Sum of Odd/Even Numbers
- Python Element at Even Position
- Python Element at Odd Position
- Python Search Element in List
- Python Largest Number in List
- Python Smallest Number in List
- Python Second Largest in List
- Python Second Smallest in List
- Python Insert Element in List
- Python Delete Element from List
- Python Multiply Numbers in List
- Swap Two Elements in List
- Python 1D Array Program
- Python Linear Search
- Python Binary Search
- Python Insertion Sort
- Python Bubble Sort
- Python Selection Sort
- Remove Duplicates from List
- Python Reverse a List
- Python Merge Two List
- Python Copy a List
- Python Conversion Programs
- Python Decimal to Binary
- Python Decimal to Octal
- Python Decimal to Hexadecimal
- Python Binary to Decimal
- Python Binary to Octal
- Python Binary to Hexadecimal
- Python Octal to Decimal
- Python Octal to Binary
- Python Octal to Hexadecimal
- Python Hexadecimal to Decimal
- Python Hexadecimal to Binary
- Python Hexadecimal to Octal
- Python Matrix Programs
- Python Add Two Matrices
- Python Subtract Two Matrices
- Python Transpose Matrix
- Python Multiply Matrices
- Python String Programs
- Python Print String
- Python Find Length of String
- Python Compare Two Strings
- Python Copy String
- Python Concatenate String
- Python Reverse a String
- Python Swap Two Strings
- Python Uppercase to Lowercase
- Python Lowercase to Uppercase
- Python Check Substring in String
- Python Count Character in String
- Count Repeated Characters
- Python Count Word in Sentence
- Python Count Each Vowels
- Python Capitalize Character
- Python Capitalize Word in String
- Python Smallest/Largest Word
- Remove Spaces from String
- Remove Duplicate Character
- Remove Vowels from String
- Remove Punctuation from String
- Python Remove Word in String
- Python Remove Duplicate Words
- WhiteSpace to Hyphens
- Replace Vowels with Character
- Replace Character in String
- Python Sort String in Alphabetical
- Sort Word in Alphabetical Order
- Extract Number from String
- Python Check Anagram Strings
- Python File Programs
- Python Read a File
- Python Write to File
- Python Append Text to File
- Python Copy Files
- Python Merge Two Files
- Python Counts Characters in File
- Python Count Words in File
- Python File Content in Reverse
- Python Lines Contains String
- Python Delete Line from File
- Python Capitalize Word in File
- Python Replace Text in File
- Replace Specific Line in File
- Python Find Size of File
- Python List Files in Directory
- Python Delete Files
- Python Misc Programs
- Python Reverse a Tuple
- Python Merge Two Dictionary
- Python bytes to String
- Python bytearray to String
- Generate Random Numbers
- Python Print Address of Variable
- Python Print Date and Time
- Python Get IP Address
- Python Shutdown/Restart PC
- Python Tutorial
- Python Tutorial
Python Program to Delete Element from a List
In this article, I've created some programs in Python, that deletes or removes an element (or multiple elements) from a list. Both element and list must be entered by user at run-time. Here are the list of programs:
- Delete an Element from a List by Value
- Delete an Element from a List by Index
- Delete an Element with all its Occurrences from List
- Delete Multiple Elements from List
Delete an Element from List by Value
This program deletes an element (entered by user) from a list (also entered by user) by value. The question is, write a Python program to delete an element from list. Here is its answer:
print("Enter 10 Elements: ") arr = [] for i in range(10): arr.append(input()) print("\nEnter the Value to Delete: ") val = input() arr.remove(val) print("\nThe New list is:") print(arr)
Here is its sample run:
Now supply the input say 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 as ten elements, and a value say 4 to delete it from the list and print the new list as shown in the snapshot given below:
Note - The append() method appends an element at the end of a list.
Note - The remove() method removes an element (by value provided as its argument) from a list.
In above program, the following code:
for i in range(10):
is used to execute the following statement:
arr.append(input())
ten times with value of i from 0 to 9. Therefore, all ten numbers entered by user as provided in the sample run, gets stored in the list arr[] in this way:
arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Now using the following statement:
arr.remove(val)
the value stored in val variable gets removed from the list arr. For example, if value of val is 4, then 4 gets deleted from the list named arr.
Delete Element from List of Given Size
This is the modified version of previous program with an extra feature added to it. For example this program allows user to define the size of list. The end used in this program, to skip inserting an automatic newline using print()
print(end="Enter the Size of List: ") tot = int(input()) arr = [] print(end="Enter " +str(tot)+ " Elements: ") for i in range(tot): arr.append(input()) print(end="\nEnter the Value to Delete: ") val = input() if val in arr: arr.remove(val) print("\nThe New list is: ") for i in range(tot-1): print(end=arr[i]+" ") else: print("\nElement doesn't exist in the List!")
Here is its sample run with user input, 5 as size of list, and 1, 2, 3, 4, 5 as five elements of list, then 4 as element to delete:
Here is another sample run with user input 12 as size of list and c, o, d, e, s, c, r, a, c, k, e, r as twelve elements of list, then c as element to delete from this list:
Note - As you can see from this sample run, the first occurrence of c gets deleted from the list. But what if user wants to delete the c at second occurrence, then we've to follow the program that deletes an element from list by index as given below.
Note - The str() method converts any type of value to a string type.
Delete an Element from List by Index
The pop() method is used to delete an element from list by index number. Whereas the remove() method is used to delete an element by its value. Let's have a look at the program given below:
print(end="Enter the Size of List: ") tot = int(input()) arr = [] print(end="Enter " +str(tot)+ " Elements: ") for i in range(tot): arr.append(input()) print(end="\nEnter the Index Number: ") index = int(input()) if index<tot: arr.pop(index) print("\nThe New list is: ") for i in range(tot-1): print(end=arr[i]+" ") else: print("\nInvalid Index Number!")
Here is its sample run with user input, 12 as size and c, o, d, e, s, c, r, a, c, k, e, r as twelve elements of list. Now to delete second c from the list, enter 5 as index number. Because second 'c' is available at fifth index. Indexing starts with 0.
The dry run of above program with same user input as provided in sample run of this program, goes like:
- Initial values, tot = 12 (entered by user), arr = ['c', 'o', 'd', 'e', 's', 'c', 'r', 'a', 'c', 'k', 'e', 'r'] (also entered by user)
- Since indexing starts with 0. That is, the for loop through which the element of list arr gets
received, starts with its i's value from 0 to 9, therefore all twelve elements of list stored in
following ways:
- arr[0] = 'c'
- arr[1] = 'o'
- arr[2] = 'd'
- arr[3] = 'e'
- arr[4] = 's'
- arr[5] = 'c'
- and so on upto
- arr[11] = 'r'
- Therefore to delete an element at 5th index, enter 5, that deletes second 'c' from the list
- When user enters 5 as index number to delete, then index=5
- Now the condition (of if) index<tot or 5<12 evaluates to be true, therefore program flow goes inside the if's body
- Inside if's body, the following statement:
arr.pop(index)
deletes the element from list, available at index number index or 5 - Now just print the new list as output
Delete an Element with all Occurrences from List
Now this program deletes all occurrences of an element by value. For example, if user enters 1, 2, 3, 2, 4, 2 as six elements, and 2 as element to delete, then all three 2s gets deleted from the list:
print(end="Enter the Size of List: ") tot = int(input()) arr = [] print(end="Enter " +str(tot)+ " Elements: ") for i in range(tot): arr.append(input()) print(end="\nEnter an Element to Delete with all Occurrences: ") num = input() if num in arr: while num in arr: arr.remove(num) print("\nThe New list is: ") tot = len(arr) for i in range(tot): print(end=arr[i] + " ") else: print("\nElement doesn't Found in the List!")
Here is its sample run with user input 6 as size and 1, 2, 3, 2, 4, 2 as six elements, and 2 as element to delete with all its occurrences:
In above program, the following block of code:
while num in arr: arr.remove(num)
states that, the statement inside the while, that is arr.remove(num) gets executed until the condition num in arr evaluates to be false. The num in arr code checks whether the value of num available in the list named arr or not. If available, then condition evaluates to be true, otherwise evaluates to be false.
Delete Multiple Elements from List
This program allows user to delete multiple elements from list at one execution. For example, if given elements of list are 1, 2, 3, 4, 5, 6, 7, 8 and if user wants to delete two elements from the list, then enter 2 as number of element to delete, and then two values say 3 and 6 to delete these two elements as shown in the program and its output given below:
print(end="Enter the Size of List: ") tot = int(input()) arr = [] print(end="Enter " +str(tot)+ " Elements: ") for i in range(tot): arr.append(input()) print(end="How many Elements to Delete ? ") noOfElement = int(input()) print(end="Enter " +str(noOfElement)+ " Elements to Delete: ") delList = [] for i in range(noOfElement): delList.append(input()) for i in range(noOfElement): if delList[i] in arr: while delList[i] in arr: arr.remove(delList[i]) print("\nThe New list is: ") tot = len(arr) for i in range(tot): print(end=arr[i] + " ")
Here is its sample run with following user inputs:
- 6 as size of list
- 1, 2, 3, 2, 3, 4 as six elements of list
- 2 as number of element to delete from list
- 2, 3 as two elements to delete from list
Let's have a look at the sample run given below:
Note - The len() returns length of thing (list) passed as its argument
In above program, I've created a list named delList, that stores list of elements (entered by user) that has to be delete from the list named arr (also entered by user). That is using indexing of delList list, I've checked whether the current element available in the original list named arr or not. If available, then delete, otherwise continue to check for next, until the last element of delList
« Previous Program Next Program »