Python - Add one to each item in list

Introduction

To change the list as we loop across it, use indexes so we can assign an updated value to each position.

Demo

L = [1, 2, 3, 4, 5] 

for i in range(len(L)):          # Add one to each item in L 
     L[i] += 1                    # Or L[i] = L[i] + 1 
print( L )

Result

Using a while loop

Demo

L = [1, 2, 3, 4, 5] 
i = 0 # from   ww  w .java  2  s.c  o m
while i < len(L): 
     L[i] += 1 
     i += 1 

print( L )

Result

Using list comprehension expression of the form:

Demo

L = [1, 2, 3, 4, 5] 

A = [x + 1 for x in L] 
print(A)# from   w w  w  .j a  v a2 s .c o  m

Result

Related Topic