CBSE Class 11: Python List 8

del (delete an element using index)

0

1

2

3

4

5

6

7

c

o

m

p

u

t

e

R

n1=[‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’]

print(n1)

#Output:  [‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

del n1[0]

print(n1)

#Output:  [‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

del n1[1]

print(n1)

#Output: [‘o’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

#count starts from 0(zero)

Example:

n=[1,2,3,4,5,6,7,8,9,10]

del n[2]

print(n)

#Output: [1, 2, 4, 5, 6, 7, 8, 9, 10]

del n[4]

print(n)

#output: [1, 2, 4, 5, 7, 8, 9, 10]

del n[7]

print(n)

#Output: [1, 2, 4, 5, 7, 8, 9]

Delete by range:

n=[0,1,2,3,4,5,6,7,8,9,10]

del n[0:2] #elements of position 0 and 1 are deleted

print(“n[0:2]”,n)

#Output: n[0:2] [2, 3, 4, 5, 6, 7, 8, 9, 10]

n=[0,1,2,3,4,5,6,7,8,9,10]

del n[0:3]

print(“n[0:3]”,n) #elements of position 0,1, and 2 are deleted

#Output: n[0:3] [3, 4, 5, 6, 7, 8, 9, 10]

n=[0,1,2,3,4,5,6,7,8,9,10]

del n[0:5]

print(“n[0:5]”,n)

#Output: n[0:5] [5, 6, 7, 8, 9, 10]

n=[0,1,2,3,4,5,6,7,8,9,10]

del n[2:5]

print(“n[2:5]”,n)

#Output: n[2:5] [0, 1, 5, 6, 7, 8, 9, 10]

n=[0,1,2,3,4,5,6,7,8,9,10]

del n[4:8]

print(“n[4:8]”,n)

#Output: n[4:8] [0, 1, 2, 3, 8, 9, 10]

n=[0,1,2,3,4,5,6,7,8,9,10]

print(n)

del n

# delete entire list

print(n)

#Output: error : NameError: name ‘n’ is not defined

Example:

n = [‘p’,’r’,’o’,’b’,’l’,’e’,’m’]

# delete one item

del n[2]

print(n)

# Output: [‘p’, ‘r’, ‘b’, ‘l’, ‘e’, ‘m’]    

# delete multiple items

del n[1:5] 

print(n)

# Output: [‘p’, ‘m’]

# delete entire list

del n      

print(n)

#Output:  Error: List not defined