How to add new element in python list using insert() extend() append() methods

 How to add new element in python list :

list methods:

insert():insert method to add the object/element at the specified position in the list,insert method accepts two parameters position and object

syntax:

insert(index,object)

Ex:

list=[30,50,60,70,80]

list.insert(3,55)

print(list)

list.insert(3,[45,66,77]) #nested index

print(list)

output:[30,50,60,55,70,80]

[30,50,60,[45,66,77],80]

extend() or append() :

extend method will accept the list of elements and add them at the end of the list

Ex:

#using extend or append

mylist = list([5, 87, 'ravi', 3.50])

mylist.extend([25, 75, 10]) 

print(mylist)

output:[5, 87, 'ravi', 3.50,25, 75, 10]


#using extend or append

mylist = list([5, 87, 'ravi', 3.50])

mylist.append([25, 75, 10])  #append add new elements to nested index

print(mylist)

output:[5, 87, 'ravi', 3.50,[25, 75, 10]]


Modify:Modify the individual item,  Modify the range of items.

Ex:

mylist = list([5, 10, 20, 30])

mylist[2]=90 #single element modified

print(mylist)

output:[5, 10, 90, 30]

 #modify from 1st index to 3th

mylist[1:3]=[56,88,99] 

print(mylist)

output:[5, 56, 88, 99, 30]

#modify from 2rd index to end

mylist[2:]=[34,55,66,77]

print(mylist)

output:[5, 56, 34, 55, 66, 77]

#modify all items

mylist=list([5,10,20,30])

for x in range(len(mylist)):

    sqr=mylist[x]*mylist[x]

    mylist[x]=sqr

print(mylist)

output:[25, 100, 400, 900]

No comments:

Post a Comment

Latest Post

How to Generate Barcode and QR code For Our Products

 మీ products కి barcode / QR code generate చేయాలంటే OPTION 1: ONLINE (No Coding – Quick) Best for small shops / beginners 👉Free websites: T...