Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Change List Item

Python – Change List Item

List in python is mutable types which means it can be changed after assigning some value. The list is similar to arrays in other programming languages. In this article, we are going to see how to change list items in python. 

Let’s understand first how to access  elements in python:

  • Accessing the first element mylist[0]
  • Accessing the second element mylist[1]
  • Accessing the last element mylist[-1] or mylist[len(mylist)-1]

Python3




# code
gfg = [ 10, 20, 30, 40, 50, 60]
  
#first element
print(gfg[0])
  
#second element
print(gfg[1])
  
#last element
print(gfg[-1])


Output:

10
20
60

Now we can change the item list with a different method:

Example 1: Change Single list item.

Approach:

  • Change first element mylist[0]=value
  • Change third element mylist[2]=value
  • Change fourth element mylist[3]=value

Code:

Python3




# list
List=[ 10, 20, 30, 40, 50, 60]
print("original list ")
print(List)
  
#changing the first value
List[0] = 11
  
#changing the second value
List[1] = 21
  
#changing the last element
List[ -1] = 61
  
print("\nNew list")
print(List)


Output:

original list 
[10, 20, 30, 40, 50, 60]

New list
[11, 21, 30, 40, 50, 61]

Example 2: Changing all values using loops.

Python3




# list
list = [ 10, 20, 30, 40, 50, 60]
print("Original list ")
print(list)
      
print("After incrementing each element of list by 2")  
  
# adding 2 to each value of list
# len method to calculate length of list
# range method is used to go upto a certain range
for i in range( len(list)):
    list[i] = list[i] + 2
  
print(list)


Output:

Original list 
[10, 20, 30, 40, 50, 60]
After incrementing each element of list by 2
[12, 22, 32, 42, 52, 62]

Example 3: Changing all values of a list using List comprehension.

Python3




# list
List_1 = [ 10, 20, 30, 40, 50]
print("Original list ")
print(List_1)
  
print("After incrementing each element of list by 2")
List_2=[ i+2 for i in List_1]
  
print(List_2)


Output:

Original list 
[10, 20, 30, 40, 50]
After incrementing each element of list by 2
[12, 22, 32, 42, 52]

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments