Skip to main content

Python: Change or Modify List

There are several ways to change or modify list items:

1. By using insert()

It is a in-built function inserts a given element at a given index in a list. Each item within a list has an index number associated with that item (starting from zero).We can modify an item within a list in Python by referring to the item’s index.

Syntax:

list_name.insert(index, element)

Example:

thislist = ["apple", "banana", "cherry"]
print("List before insert: ",thislist)

thislist[1] = "papaya"
print("List after insert: ",thislist)

Output:

List before insert:  ['apple', 'banana', 'cherry']
List after insert:  ['apple', 'papaya', 'cherry']

2. By using append()

We can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method.

mylist = ['physics','chemistry']
print("List before append: ",mylist)

mylist.append('biology')
print("List after append: ",mylist)

Output:

List before append:  ['physics', 'chemistry']
List after append:  ['physics', 'chemistry', 'biology']

3. By using Index no

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

mylist = [1,2,3,4,5]
print("list before: ",mylist)

mylist[2] = 6
print("list after: ",mylist)

Output:

list before:  [1, 2, 3, 4, 5]
list after:  [1, 2, 6, 4, 5]

4. By using extend()

It is used to  adds all the elements of an iterable (list, tuple, string etc.) to the end of the list.

languages = ['French', 'English']
print("List before extend: ",languages);

languages.extend(['Hindi'])
print("List after extend: ",languages);

Output:

List before extend:  ['French', 'English']
List after extend:  ['French', 'English', 'Hindi']

Tags
Submitted by devanshi.srivastava on June 9, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.