Python – Change List Item
Last Updated :
02 Dec, 2020
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
gfg = [ 10 , 20 , 30 , 40 , 50 , 60 ]
print (gfg[ 0 ])
print (gfg[ 1 ])
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 = [ 10 , 20 , 30 , 40 , 50 , 60 ]
print ( "original list " )
print ( List )
List [ 0 ] = 11
List [ 1 ] = 21
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 = [ 10 , 20 , 30 , 40 , 50 , 60 ]
print ( "Original list " )
print ( list )
print ( "After incrementing each element of list by 2" )
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_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]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...