Wednesday, January 6, 2021

How To Change List Items In Python


Like many other programming languages, change value in List is possible in Python.

Change Item Value

To change the value of a specific item, refer to the index number:

 Example

Change the second item:

 mylist = ["Assam","Banaras","Chennai"]

mylist[1] = "Bangalore"

Present list will be ["Assam","Bangalore","Chennai"]


 Change a Range of Item Values

To change the value of items within a specific range, we have to specify the start and end index with new values. Changes will be done on consecutive indexes starting from start index to end index -1. 

Example

Change the values "Banaras" and "Chennai" with the values "blackcurrant" and "watermelon":

mylist = ["Assam","Banaras","Chennai", "Delhi","Kolkata","Mumbai"]

mylist[1:3] = ["Bihar", "Kerala"]

 The list will be ["Assam","Bihar","Kerala", "Delhi","Kolkata","Mumbai"]

 

Dynamic insertion is possible in Python. If we want to insert more items than you replace items, the new items will be inserted on consecutive locations and the the remaining items at right side will move accordingly. 

Example

Change the second value by replacing it with two new values: 

mylist = ["Assam","Banaras","Chennai"]

mylist[1:2] = ["Bihar", "Kerala"] (specified location was 1 to 1)

The list will be ["Assam","Bihar","Kerala", "Chennai"] ("Bihar" will be at index 1, "Kerala" at index 2 , "Chennai" at index 3) 

The length of the list will automatically change. 

Like dynamic insertion, dynamic deletion is possible in Python. If we want to insert less items than you replace items, the new items will be inserted on specified indexes.

 

Example

Change the second and third value by replacing it with one value: 

mylist = ["Assam","Banaras","Chennai"]

mylist[1:3] = ["Bihar"]

The list will looks like: ["Assam","Bihar"]

 

Insert Items

To insert a new list item, without replacing any of the existing values, we can use the insert() method. 

The insert() method inserts an item at the specified index:

 

Example

Insert "Bihar" as the third item:

mylist = ["Assam","Banaras","Chennai"]

mylist.insert(2, "Bihar") ( "Bihar" will be inserted at index 2 and "Chennai" will automatically shited to index 3)

The list will be ["Assam","Banaras","Bihar","Chennai"]

Append Items

To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

mylist = ["Assam","Banaras","Chennai"]
mylist.append("Mumbai")

Output will be: The list will be ["Assam","Banaras","Bihar","Mumbai"] 

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner