How to manipulate list in python

How to manipulate list in python

How to manipulate list in python

We can manipulate list in python using function append(), insert(), and by index

Manipulate list in python

#1. append()

append() function is used to add a new element in the list at the last position. 

country = [ ‘India’, ‘USA’, ‘Australia’, ‘Canada’ ]

print( country )

country.append(“UK”)

print( ‘ After adding a new country ‘ )

print( country )

Output

[ ‘India’, ‘USA’, ‘Australia’, ‘Canada’ ]

After adding a new country

[ ‘India’, ‘USA’, ‘Australia’, ‘Canada’, ‘UK’ ]

#2. insert()

insert() function is used to add a new element in list at given position.

color = [ ‘Green’, ‘Red’, ‘Black’, ‘Yellow’ ]

print( color )

color.insert(‘Blue’)

print( ‘ After adding a new color’ )

print( color)

Output

 [ ‘Green’, ‘Red’, ‘Black’, ‘Yellow’ ]

After adding a new color

[ ‘Green’, ‘Red’, ‘Black’, ‘Yellow’, ‘Blue’ ]

#3 By using index

We can modify a list by using its index.
list = [10, 20, 30, 40 ]
print( list )
lis[3] = 50
print( ‘ After adding a new element ‘ )
print( list )

Output

[10, 20, 30, 40 ]
After adding a new element
[10, 20, 30, 50, 40 ]
 
 
How to Modify multiple elements in Python list


Important Links: Informatics Practices

If you like my post please share it with your friends by simply clicking the below social media button, and Don’t forget to comment so we will update ourselves.

Share in a Single Click

Leave a Reply

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