You are on page 1of 4

6-10-2023

Friday, October 6, 2023 7:04 PM

index()

It gives the index value of first occurrence of the element

l=[22,33,44,22,44,55]
print(l.index(22))

output:
0

l=[22,33,44,22,44,55]
print(l.index(44))

output:
2

l=[44,33,44,55,77]
print(l.index(99))

If a particular element is not available in the list we will get valueerror.

ValueError: 99 is not in list

Write a program to display the element along the index value.

l=[1,2,3,1,1,1,4]
x=int(input('enter any element to find index:'))
if x in l:
i=l.index(x)
print('{} element first occurrence index is {}'.format(x,i))
else:
print("specified element is not found")

output:
D:\>py program1.py
enter any element to find index:1
1 element first occurrence index is 0

D:\>py program1.py
enter any element to find index:99
Python 22 batch 7 pm Page 1
enter any element to find index:99
specified element is not found

D:\>py program1.py
enter any element to find index:34
specified element is not found

append():

append() is used to add the elements inside the list.

***The append() takes only one value at a time

append() adds the element at the end of list.

l=[]
l.append(45)
print(l)

l=[]
l.append(45)
l.append(66)
l.append(77)
print(l)

D:\>py program1.py
[45, 66, 77]

Postmortem of append()

Question asked in TCSX-2020

l=[]
l.append(10,)
print(l)
Mathematical applications
options
data science
a.Error
b.[10]
c.[10,]
Python 22 batch 7 pm Page 2
data science
a.Error
b.[10]
c.[10,] (10)->int
(10)+(20)=30
10+20=30
10+(20)=30
(10)+20=30

append() takes the collection related datatypes


as arguments

l=[]
l.append({2,3,5,6,7,8})
print(l)

output:
D:\>py program1.py
[{2, 3, 5, 6, 7, 8}]

l=[]
l.append((2,3,4,5,6,7,8))
print(l)

output:
D:\>py program1.py
[(2, 3, 4, 5, 6, 7, 8)]

l=[45,66]
l.append('a')
print(l)

D:\>py program1.py
[45, 66, 'a']

write a program to add elements inside a list which are divisible by 10 upto 100
l=[]
for i in range(101):
if i%10==0:
l.append(i)
print(l)

Python 22 batch 7 pm Page 3


if i%10==0:
l.append(i)
print(l)

output:
D:\>py program1.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

insert()

insert() adds the element inside the list at a particular index

syntax:
insert(index,element)

l=[10,20,30,40]
l.insert(1,777)
print(l)

output:
D:\>py program1.py
[10, 777, 20, 30, 40]

l=[10,20,30,40]
l.insert(3,444)
print(l)

output:
D:\>py program1.py
[10, 20, 30, 444, 40]

Python 22 batch 7 pm Page 4

You might also like