Questions

How do I Delete a Command in Python?

Python del statement can also be used to delete a specific element from the iterable object, or it can also be used to delete a range of data values from the iterables. This can be done by using the Indexing method. Index values need to be specified in order to delete specific data values.

Example

                    

num_list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]
print('Original List:', num_list)
print()

# deleting 4th value in the list
del num_list[3]
print('Updated List:', num_list)

# deleting values from position 3 to 6
del num_list[3:7]
print('New updated list:', num_list)

# deleting all values of the list
del num_list[:]
print(num_list)

Output

                    

Original List: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]

Updated List: [1, 3, 5, 9, 11, 13, 15, 17, 19, 21, 23, 25]
New updated list: [1, 3, 5, 17, 19, 21, 23, 25]
[]

Note – Single items and values inside the tuple and string cannot be deleted. Tuples and strings are immutable objects, meaning they can’t be modified after they’ve been created. However, we can delete an entire tuple or a string.

Example

                    

my_tuple = (1, 'John', 2, 'Riya', 3, 'Sam')

del my_tuple[2]
print(my_tuple)

Output

                    

Traceback (most recent call last):
File "", line 3, in 
TypeError: 'tuple' object doesn't support item deletion

Related Questions

Related Topics

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.